Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file into string in java?

Tags:

java

I have read a file into a String. The file contains various names, one name per line. Now the problem is that I want those names in a String array.

For that I have written the following code:

String [] names = fileString.split("\n"); // fileString is the string representation of the file 

But I am not getting the desired results and the array obtained after splitting the string is of length 1. It means that the "fileString" doesn't have "\n" character but the file has this "\n" character.

So How to get around this problem?

like image 396
Yatendra Avatar asked Nov 01 '09 10:11

Yatendra


People also ask

How do you load a file in Java?

Example 1: Java Program to Load a Text File as InputStream txt. Here, we used the FileInputStream class to load the input. txt file as input stream. We then used the read() method to read all the data from the file.

How do I read a local text file in Java?

There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.

What method is best for reading the entire file into a single string?

The read() method reads in all the data into a single string. This is useful for smaller files where you would like to do text manipulation on the entire file. Then there is readline() , which is a useful way to only read in individual lines, in incremental amounts at a time, and return them as strings.


2 Answers

What about using Apache Commons (Commons IO and Commons Lang)?

String[] lines = StringUtils.split(FileUtils.readFileToString(new File("...")), '\n'); 
like image 173
Romain Linsolas Avatar answered Sep 30 '22 17:09

Romain Linsolas


The problem is not with how you're splitting the string; that bit is correct.

You have to review how you are reading the file to the string. You need something like this:

private String readFileAsString(String filePath) throws IOException {         StringBuffer fileData = new StringBuffer();         BufferedReader reader = new BufferedReader(                 new FileReader(filePath));         char[] buf = new char[1024];         int numRead=0;         while((numRead=reader.read(buf)) != -1){             String readData = String.valueOf(buf, 0, numRead);             fileData.append(readData);         }         reader.close();         return fileData.toString();     } 
like image 33
b.roth Avatar answered Sep 30 '22 17:09

b.roth