I've made the following Java-class just for getting some practice with the creation and reading of files.
package modul;
import static java.lang.System.*;
import java.io.*;
public class Sandbox {
public static void main (String[] args) {
// I found out that the project directory is the
// working directory by default.
// Is there a way to change the working directory in Java?
// So that all instructions become relative to that directory.
String currentDir = System.getProperty("user.dir") + "/src/modul/";
String fileName = "lorem.txt";
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(currentDir + fileName)));
// Write a few lines of dummy-text ...
writer.println("The very first line of text.");
writer.println("----------------------------");
writer.println("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.");
writer.println("Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.");
writer.println("In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.");
// Is it enough just closing the PrintWriter?
// What's about the BufferedReader and the FileReader?
// Are they closed automatically?
writer.close();
// Now open the created file. Read and print it's
// content to stdout.
BufferedReader reader = new BufferedReader(new FileReader(currentDir + fileName));
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
out.println(++lineNumber + ": " + line);
}
// Is it fair enough just closing the Reader?
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Although it won't serve a real use-case it's important for me to know if everything is done in a good way. Or does I have to improve the code?
Moreover: Are there ways to accomplish writing-, reading-operations more efficient? Respectively in a simpler way?
A few more questions I've still got about Java IO-operations I've added as comments within the code.
All comments, hints and recommendations of more experienced Java-devs much appreciated.