FileInputStream如何获取File的内容?

时间:2012-07-14 16:12:11

标签: java file fileinputstream

我有一个文件f,我需要将其影响为FileInputStream fs

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

但是我收到了这个错误:

Cannot cast from File to FileInputStream

fs如何获取f的内容?

3 个答案:

答案 0 :(得分:14)

诀窍是:

FileInputStream fs = new FileInputStream(f);

答案 1 :(得分: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);

答案 2 :(得分:1)