简体   繁体   中英

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

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 eg " ".

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

Thank you in advance.

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.

You can read directly into the buffer and then create a String from the buffer:

    File f = new File(filePath);
    FileInputStream fin = new FileInputStream(f);
    byte[] buffer = new byte[(int) f.length()];
    new DataInputStream(fin).readFully(buffer);
    fin.close();
    String s = new String(buffer, "UTF-8");

You could add this code:

return new String(buffer).replaceAll("(\r\n|\r|\n|\n\r)", "<br>");

Is this what you are looking for?

The code will read the file contents as they appear in the file - including line breaks. If you want to change the breaks into something else like displaying in html etc, you will either need to post process it or do it by reading the file line by line. Since you do not want the latter, you can replace your return by following which should do the conversion -

return (new String(buffer)).replaceAll("\r[\n]?", "<br>");

You should try org.apache.commons.io.IOUtils.toString(InputStream is) to get file content as String. There you can pass InputStream object which you will get from

getAssets().open("xml2json.txt")    *<<- belongs to Android, which returns InputStream* 

in your Activity. To get String use this:

String xml = IOUtils.toString((getAssets().open("xml2json.txt")));

So,

String xml = IOUtils.toString(*pass_your_InputStream_object_here*);

I agree with the general approach by @Sanket Patel, but using Commons I/O you would likely want File Utils .

So your code word look like:

String myString = FileUtils.readFileToString(new File(filePath));

There is also another version to specify an alternate character encoding.

StringBuilder sb = new StringBuilder();
        try {
            InputStream is = getAssets().open("myfile.txt");
            byte[] bytes = new byte[1024];
            int numRead = 0;
            try {
                while((numRead = is.read(bytes)) != -1)
                    sb.append(new String(bytes, 0, numRead));
            }
            catch(IOException e) {

            }
            is.close();
        }
        catch(IOException e) {

        }

your resulting String : String result = sb.toString();

then replace whatever you want in this result .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM