Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with files in java

Tags:

java

file-io

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.

like image 626
Jjang Avatar asked Aug 31 '26 06:08

Jjang


1 Answers

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.
  • To check if a file exists, use: file.exists().
  • To check if the file object refers to a file or a directory, use: file.isDirectory() and file.isFile().
  • To create a new file, use: file.createNewFile().
  • To create a directory, use: file.mkdirs().
  • You may need to use the constructors PrintWriter(File file, String csn) and InputStreamReader(InputStream in, Charset cs) to determine the charset.
like image 129
Eng.Fouad Avatar answered Sep 03 '26 02:09

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!