6

I have a file f and I need to affect it into a 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 can fs get the content of f?

A.H.
  • 61,009
  • 14
  • 85
  • 115

3 Answers3

14

The trick is this:

FileInputStream fs = new FileInputStream(f);
A.H.
  • 61,009
  • 14
  • 85
  • 115
4

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);
ioreskovic
  • 5,310
  • 5
  • 36
  • 67
1

Here I found the solution :

http://journals.ecs.soton.ac.uk/java/tutorial/java/io/filestreams.html