【问题标题】:Return the text of a file as a string? [duplicate]将文件的文本作为字符串返回? [复制]
【发布时间】:2011-07-11 12:14:04
【问题描述】:

可能重复:
How to create a Java String from the contents of a file

是否可以处理多行文本文件并将其内容作为字符串返回?

如果可以的话,请告诉我怎么做。


如果您需要更多信息,我正在研究 I/O。我想打开一个文本文件,处理其内容,将其作为字符串返回并将 textarea 的内容设置为该字符串。

有点像文本编辑器。

【问题讨论】:

    标签: java string file text return


    【解决方案1】:

    使用 apache-commons FileUtils 的readFileToString

    【讨论】:

    • 虽然是正确且最简单的方法,但这个家伙正在“玩弄 I/O”——所以这并没有多大帮助。
    • 可能是真的。但是,他可以根据所指出的内容提取源代码并从中学习。没有必要在这里重新发明轮子,试图解释打开文件并将其内容读入字符串的无限不同方式。
    【解决方案2】:
    String data = "";
    try {
        BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
        StringBuilder string = new StringBuilder();
        for (String line = ""; line = in.readLine(); line != null)
            string.append(line).append("\n");
        in.close();
        data = line.toString();
    }
    catch (IOException ioe) {
        System.err.println("Oops: " + ioe.getMessage());
    }
    

    记得先import java.io.*

    这会将文件中的所有换行符替换为 \n,因为我认为没有任何方法可以获取文件中使用的分隔符。

    【讨论】:

      【解决方案3】:

      在此处查看 java 教程 - http://download.oracle.com/javase/tutorial/essential/io/file.html

      Path file = ...;
      InputStream in = null;
      StringBuffer cBuf = new StringBuffer();
      try {
          in = file.newInputStream();
          BufferedReader reader = new BufferedReader(new InputStreamReader(in));
          String line = null;
      
          while ((line = reader.readLine()) != null) {
              System.out.println(line);
              cBuf.append("\n");
              cBuf.append(line);
          }
      } catch (IOException x) {
          System.err.println(x);
      } finally {
          if (in != null) in.close();
      }
      // cBuf.toString() will contain the entire file contents
      return cBuf.toString();
      

      【讨论】:

      • StringBuffer 已被弃用,你知道。
      【解决方案4】:

      类似的东西

      String result = "";
      
      try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
        dis = new DataInputStream(bis);
      
        while (dis.available() != 0) {
      
          // Here's where you get the lines from your file
      
          result += dis.readLine() + "\n";
        }
      
        fis.close();
        bis.close();
        dis.close();
      
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      
      return result;
      

      【讨论】:

      • 字符串连接以二次时间运行。请改用StringBuilder
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 2016-07-25
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多