【问题标题】:How can a FileInputStream get the content of File?FileInputStream 如何获取 File 的内容?
【发布时间】:2012-07-14 16:12:11
【问题描述】:

我有一个文件f,我需要将它转换成FileInputStream fs

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

但我得到这个错误:

Cannot cast from File to FileInputStream

fs如何获取f的内容?

【问题讨论】:

    标签: java file fileinputstream


    【解决方案1】:

    诀窍是这样的:

    FileInputStream fs = new FileInputStream(f);
    

    【讨论】:

      【解决方案2】:

      您可以使用这种方法:

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

      【讨论】:

        【解决方案3】:

        【讨论】:

          猜你喜欢
          • 2020-12-10
          • 1970-01-01
          • 2011-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-13
          • 2021-09-05
          相关资源
          最近更新 更多