简体   繁体   中英

How can a FileInputStream get the content of File?

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 ?

诀窍是:

FileInputStream fs = new FileInputStream(f);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM