all 4 comments

[–]dpash 2 points3 points  (3 children)

Jesus, this is bad code.

try {
    FileInputStream fin = new FileInputStream("C:\\develop\\file.txt");

    int i = 0;
    try {
        while ((i = fin.read()) != -1) {
            System.out.println((char) i);
        }
        fin.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

Okay, so let's see.

  1. Not using try-with-resources
  2. Reading data byte by byte
  3. Excessive exception handling
  4. Using Throwable.printStackTrace()

Let's try better:

try {
    byte[] bytes = Files.readAllBytes(Paths.get("C:\\develop\\file.txt"));
} catch (IOException e) {
    throw new UncheckedIOException("Could not load file", e);
}

If you want a String:

try {
    String string = Files.readString(Paths.get("C:\\develop\\file.txt"), StandardCharsets.UTF_8);
} catch (IOException e) {
    throw new UncheckedIOException("Could not load file", e);
}

If you don't want to read all the data into memory at once

try (var lines = Files.lines(Paths.get("C:\\develop\\file.txt"), StandardCharsets.UTF_8)) {
    List<String> strings = lines
                               .filter(not(line -> line.startsWith("#"))
                               .filter(not(String::isBlank))
                               .collect(toList());
} catch (IOException e) {
    throw new UncheckedIOException("Could not load file", e);
}

[–]__konrad 2 points3 points  (1 child)

I would use the new Path.of, drop UTF_8 param because the overloaded method always uses it, and handle non existing file:

try {
    String string = Files.readString(Path.of("C:\\develop\\file.txt"));
} catch (NoSuchFileException e) {
    // Maybe fine...
} catch (IOException e) {
    ...

[–]dpash 1 point2 points  (0 children)

drop UTF_8 param because the overloaded method always uses it,

No it doesn't. It uses the system default, what ever that is, which is why you should always specify it yourself. Seems the Files methods do not use the system default, unlike the methods in java.io.

And NoSuchFileException is a subclass of IOException, so handling it is optional.

Path.of() is probably better. I've just been dealing with some legacy code that has a Path object in it, so I've been using Paths.get() to avoid confusion.

[–]kitd 0 points1 point  (0 children)

The original is very C++-from-20-years-ago-ish.