2

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 that as a String and set the contents of a textarea to that string.

Kind of like a text editor.

0

4 Answers 4

2

Use apache-commons FileUtils's readFileToString

Sign up to request clarification or add additional context in comments.

2 Comments

Although correct and the easiest way to go, the guy is "playing around with I/O" - so this doesn't help much.
Probably true. However, he could just pull up the source code on what was pointed out and learn from that. There's no need to re-invent the wheel here trying to explain the infinite different ways to open a file and read its contents into a string.
0

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

1 Comment

StringBuffer is deprecated you know.
0

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;

1 Comment

String concatenation runs in quadratic time. Use a StringBuilder instead.
0
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.