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.

Community
  • 1
  • 1
JT White
  • 517
  • 4
  • 9
  • 21

4 Answers4

2

Use apache-commons FileUtils's readFileToString

Harsha Hulageri
  • 2,810
  • 1
  • 22
  • 23
  • Although correct and the easiest way to go, the guy is "playing around with I/O" - so this doesn't help much. – Lucas Zamboulis Mar 09 '11 at 00:42
  • 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. – rfeak Mar 09 '11 at 01:01
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;
fredley
  • 32,953
  • 42
  • 145
  • 236
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();
sdc
  • 89
  • 2
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.

Peter C
  • 6,219
  • 1
  • 25
  • 37