#Reading from and writing to a file in java

1 messages · Page 1 of 1 (latest)

gusty mirage
#

Hello, I need to learn how to read from a file and how to write from a file in Java. I just learn how to do it using BufferReader and BufferWrite. My question is, is there anything else that I need to learn ? When I try to look for resources on the internet, there are so many things related to file handling so I'm a bit confused of what I need to learn

elfin mauveBOT
#

<@&987246399047479336> please have a look, thanks.

wind jetty
#

yeah. sounds like u learned the old way

#

prefer using NIO instead:

elfin mauveBOT
#

File IO in Java should be done preferably with NIO (Java 7+), revolving around the classes Files and Path; and not with the old interface File, BufferedReader, FileReader and similar.

NIO is simple to use. The path to a file is represented using the Path class:

Path path = Path.of("myFile.txt");

All file operations can be found in the Files class:

// Reading
List<String> allLines = Files.readAllLines(path);
// or as a single string
String content = Files.readString(path);
// or with a stream
try (Stream<String> stream = Files.lines(path)) {
  stream.forEach(System.out::println);
}

// Writing
Files.write(path, lines);
// or as a single string
Files.writeString(path, "hello world");
// or with extra options
Files.writeString(path, "hello world",
  StandardOpenOption.WRITE,
  StandardOpenOption.CREATE,
  StandardOpenOption.APPEND);

If you need more control over the process, you can fallback to the old interface, but prefer using the bridge methods from NIO (Files.newBufferedReader, Files.newInputStream, path.toFile() and similar) to benefit from advantages such as correct encoding and better error detection.

Here is a simple example of how to read a file line-wise with the old interface

try (BufferedReader br = Files.newBufferedReader(path)) {
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
}

it is way more verbose than NIO but it gives more control.

You must not forget to close file handles, even in all exceptional cases. Closing a handle manually is very hard, which is why you should always use try-with-resources for this to let Java automatically close the handle for you:

try (SomeResource resource = ...) {
  ...
} // Automatically closed here, even in exceptional cases
gusty mirage
#

hmmm is using NIO a better choice ? I found that there are lot more of syntax here

wind jetty
#

NIO is easier to use, much shorter code to write and also safer

#

u cant beat single-line file writing like

#
Files.writeString(Path.of("foo.txt"), "hello world");
#

can u

#

or single line file reading

#
List<String> allLines = Files.readAllLines(Path.of("foo.txt"));
gusty mirage
wind jetty
#

a list is sth similar to an array

#

for starters, u can iterate it

#
for (String line : allLines) {
  System.out.println(line);
}
#

or with an indexed for loop as ur prob used to:

#
for (int i = 0; i < allLines.size(); i++) {
  System.out.println(allLines.get(i));
}
gusty mirage
#

compare to the use of BufferReader where we need a loop to know the end of the file, here when we use NIO, we don't need a loop ?

wind jetty
#

instead of reading the file line by line, u read it entirely

#

and then process the results afterwards urself

#

while the file is closed again

#

thats also faster

gusty mirage
#

Yeah I see, so using NIO to read and write to files, we only need these 2? If so, yeah you are right that pretty simple, I just have to become more familiar with the syntax used

wind jetty
gusty mirage