Reviewed several lectures, read several articles.

And I did not understand how to create, edit and open a file.

Can you paint each item?

  • one
    Text file or arbitrary? - post_zeew
  • Text file - Romag

1 answer 1

Write data to file:

FileWriter fileWriter = new FileWriter("SimpleTextFile.txt", false); fileWriter.write("Example text"); fileWriter.close(); 

The above constructor for the FileWriter class is:

 FileWriter(String fileName, boolean append) 

Its parameters are:

  • fileName - the path to the file;
  • append is a flag; if true , then the data is added to the file; if false is overwritten .

If the file SimpleTextFile.txt does not exist, it will be created.

Reading data from file:

 try { BufferedReader bufferedReader = new BufferedReader(new FileReader("SimpleTextFile.txt")); StringBuilder stringBuilder = new StringBuilder(); String currentLine; while ((currentLine = bufferedReader.readLine()) != null) { stringBuilder.append(currentLine + "\n"); } bufferedReader.close(); String text = stringBuilder.toString().trim(); } catch (FileNotFoundException exception) { System.out.println("File not found!"); } 

The text contained in the file will be in the variable text .

If the SimpleTextFile.txt file does not exist, a FileNotFoundException exception will be FileNotFoundException .

  • Thank you so much, it became much better to understand after reading everything that you described. Thanks again :) - Romag