I have an array of strings. I want to save those strings in a file. The problem is, I need to make a new file called db.txt (only if it doesn't exist), then somehow write strings to it.
And then later I want to be able to read strings from that file and insert them to the array.
Inserting and using array is not the question, but the question is how do I mess with the files? How do I create a new text file (if not existing already), how do I write to it and how do I read from it?
Tried to learn it by myself but I've seen so many ways on the Internet and got confused.
Here is an example of writing to a text file:
File file = new File("./db.txt");
PrintWriter pw = new PrintWriter(file, true); // true for auto-flush
pw.println("Line 1");
pw.println("Line 2");
pw.println("Line 3");
pw.close();
In case you want to append to existing text file:
File file = new File("./db.txt");
FileWriter fw = new FileWriter(file, true); // true for appending
PrintWriter pw = new PrintWriter(fw, true); // true for auto-flush
pw.println("Line 4");
pw.println("Line 5");
pw.println("Line 6");
pw.close();
To read from text file:
File file = new File("./db.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line1 = br.readLine();
String line2 = br.readLine();
String line3 = br.readLine();
br.close();
Also consider the following:
PrintWriter does not create new file if it does not exist, while FileWriter does.file.exists().file.isDirectory() and file.isFile().file.createNewFile().file.mkdirs().PrintWriter(File file, String csn) and InputStreamReader(InputStream in, Charset cs) to determine the charset.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With