Wednesday, October 14, 2015

Working with files in Java

Really obvious things for a lot of developers - but I still want to keep them here. You can blame me for not keeping them in mind - but I still don't have an answer what for :)

Reading from file:

public void readFile() {
        String str;
        try {
            File file = new File("Full path to file here");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            while ((str = bufferedReader.readLine()) != null) {
                isTestHeaderString(str);
            }
            bufferedReader.close();
        } catch (IOException exception) {
            exception.toString();
        }
    }


Writing to file:

public void writeToFile() {
    try {
        new File("Path do directory if we need that").mkdir();
        File file = new File("Path & name for file");
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.append("What we actually want to write goes here");
        writer.close();
   } catch (IOException exception) {
        exception.toString();
   }
}

I'm not adding here any synchronisation / multi threading things - might add them later.


No comments:

Post a Comment