How can a FileInputStream get the contents of a file?

I have a file fand I need to work on it in FileInputStream fs:

File f = new File("C:/dir/foo.txt");
FileInputStream fs = (FileInputStream)f;

But I get this error:

Cannot cast from File to FileInputStream

How fsto get the content f?

+5
source share
3 answers

The trick is this:

FileInputStream fs = new FileInputStream(f);
+13
source

You can use this approach:

    BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File("text.txt")))));

    String line = null;

    while ((line = reader.readLine()) != null) {
        // do something with your read line
    }

or this one:

    byte[] bytes = Files.readAllBytes(Paths.get("text.txt"));
    String text = new String(bytes, StandardCharsets.UTF_8);
+3
source
+1
source

All Articles