Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a .txt file into a single Java string while maintaining line breaks?

Tags:

java

string

file

Virtually every code example out there reads a TXT file line-by-line and stores it in a String array. I do not want line-by-line processing because I think it's an unnecessary waste of resources for my requirements: All I want to do is quickly and efficiently dump the .txt contents into a single String. The method below does the job, however with one drawback:

private static String readFileAsString(String filePath) throws java.io.IOException{
    byte[] buffer = new byte[(int) new File(filePath).length()];
    BufferedInputStream f = null;
    try {
        f = new BufferedInputStream(new FileInputStream(filePath));
        f.read(buffer);
        if (f != null) try { f.close(); } catch (IOException ignored) { }
    } catch (IOException ignored) { System.out.println("File not found or invalid path.");}
    return new String(buffer);
}

... the drawback is that the line breaks are converted into long spaces e.g. "                                 ".

I want the line breaks to be converted from \n or \r to <br> (HTML tag) instead.

Thank you in advance.

like image 368
slashline Avatar asked May 25 '11 14:05

slashline


1 Answers

What about using a Scanner and adding the linefeeds yourself:

sc = new java.util.Scanner ("sample.txt")
while (sc.hasNext ()) {
   buf.append (sc.nextLine ());
   buf.append ("<br />");
}

I don't see where you get your long spaces from.

like image 104
user unknown Avatar answered Oct 06 '22 12:10

user unknown