6

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

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

但我得到这个错误:

Cannot cast from File to FileInputStream

怎样才能fs得到内容f

4

3 回答 3

14

诀窍是这样的:

FileInputStream fs = new FileInputStream(f);
于 2012-07-14T16:13:51.680 回答
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);
于 2012-07-14T16:40:17.747 回答
1

在这里我找到了解决方案:

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

于 2012-07-14T16:33:12.957 回答