开发者

Return the text of a file as a string? [duplicate]

开发者 https://www.devze.com 2023-02-15 11:39 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: How to create a Java String from the contents of a file
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to create a Java String from the contents of a file

Is it possible to process a multi-lined text file and return its contents as a string?

If this is possible, please show me how.


If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return th开发者_开发知识库at as a String and set the contents of a textarea to that string.

Kind of like a text editor.


Use apache-commons FileUtils's readFileToString


Check the java tutorial here - 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();


Something along the lines of

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;


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

Just remember to import java.io.* first.

This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消