如何使用FileInputStream获取文件的内容?

6

我有一个文件f,需要将其转换为FileInputStream fs

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

但我遇到了这个错误:
Cannot cast from File to FileInputStream

如何使用fs获取f的内容?
3个回答

14
这个技巧就是:
FileInputStream fs = new FileInputStream(f);

4
你可以采用以下方法:

您可以使用此方法:

    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
    }

或者这个:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接