BufferedReader multiple lines as one String - java

I am trying to read multiple lines from a file into an ArrayList as a String.
What I aim to do is to make it so the program reads from a file line by line until the reader sees a specific symbol (- in this case) and saves those rows as one single String. the code below makes every row a new string that it later adds to the list instead.
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
carList.add(Arrays.toString(splited));
}
for (String carList2 : carList) {
System.out.println(carList2);
System.out.println("x");
}

First, you need to check if the read line contains "-".
If it doesn't, concatenate the line with the previous ones.
If it does, concatenate only the first part of the line with the previous line.
This is a quick implementation:
BufferedReader br = null;
br = new BufferedReader(new FileReader(file));
String read;
String concatenatedLine = "";
while ((read = br.readLine()) != null) {
String[] splited = read.split("-");
// if line doesn't contains "-", splited[0] and read are equals
concatenatedLine += splited[0];
if (splited.length > 1) {
// if read line contains "-", there will be more than 1 element
carList.add(Arrays.toString(splited)); // add to the list
// store the second part of the line, in order to add it to the next ones
concatenatedLine = splited[1];
}
}
Note the output could not be what is expected if a line contains more than one -.
Also, concatenating String using + is not the best way to do it, but I let you find out more about that.

It's not very clear for me what is the output you desire.
If you would like to have each customer on one string without "-"
then you could try the following code:
while ((read = br.readLine()) != null) {
String splited = read.replace("-", " ");
carList.add(splited);
}

Related

Read from file with BufferedReader

Basically I've got an assignment which reads multiple lines from a .txt file.
There are 4 values in the text file per line and each value is separated by 2 spaces.
There are about 10 lines of data in the file.
After taking the input from the file the program then puts it onto a Database. The database connection functionality works fine.
My issue now is with reading from the file using a BufferedReader.
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line. And if I don't use them then there's an exception as the next input is of type String.
I have contemplated using a Scanner with the .hasNextLine() method.
Any thoughts on what could be the problem and how to fix it?
Thanks.
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line = null;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
String id = split[0];
nameFromFile = split[1];
String year = split[2];
String mark = split[3];
idFromFile = Integer.parseInt(id);
yearOfStudyFromFile = Integer.parseInt(year);
markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
Edit: There was an error in the formatting of the .txt file. a missing value.
But now I get an ArrayOutOfBoundsException.
Edit edit: Another error in the .txt file! Turns out there was a single space instead of a double. It seems to be working now. But any advice on how to deal with file errors like this in the future?
The issue is that if I uncomment any 1 of the 3 lines at the bottom the BufferedReader reads every other line.
Correct. If you put any of those lines of code in, the line of text read will be thrown away and not processed. You're already reading in the while condition. You don't need another read. If you put any of those lines in, they will be thrown away and not proce
A compilable version of the code posted could be
public void read() throws IOException {
File file = new File(FILE_INPUT_NAME);
FileReader fr = new FileReader(file);
BufferedReader readFile = new BufferedReader(fr);
String line;
while ((line = readFile.readLine()) != null) {
String[] split = line.split(" ", 4);
if (split.length != 4) { // Not enough tokens (e.g., empty line) read
continue;
}
String id = split[0];
String nameFromFile = split[1];
String year = split[2];
String mark = split[3];
int idFromFile = Integer.parseInt(id);
int yearOfStudyFromFile = Integer.parseInt(year);
int markFromFile = Integer.parseInt(mark);
//line = readFile.readLine();
//readFile.readLine();
//System.out.println(readFile.readLine());
}
}
The above uses a single space (" " instead of the original " "). To split on any number of changes, a regular expression can be used, e.g. "\\s+". Of course, exactly 2 spaces can also be used, if that reflects the structure of the input data.
What the method should do with the extracted values (e.g., returning them in an object of some type, or saving them to a database directly), is up to the application using it.

File reader in eclipse

Can anyone tell me why my code never reads the 2nd line of my file? if my 2nd line in the file (for example .txt file) start at a new line and indent that line, it will not read it.But if it is in a new line and it isn't indented , it will read. also it reads 3rd line fine. Is it something with the while loop ?
Scanner keyboard = new Scanner (System.in);
System.out.println("Input the file name");
String fileName = keyboard.nextLine();
File input = new File (fileName);
BufferedReader reader = new BufferedReader(new FileReader(input));
String content = reader.readLine();
content.replaceAll("\\s+","");
while (reader.readLine() != null) {
content = content + reader.readLine();
}
System.out.println(content);
See my comments in the code below.
String content = reader.readLine(); //here you read a line
content.replaceAll("\\s+","");
while (reader.readLine() != null) //here you read a line (once per loop iteration)
{
content = content + reader.readLine(); //here you read a line (once per loop iteration)
}
As you can see, you are reading the second line in the beginning of your while loop, and you are checking if it is equal to null before moving on. However, you do nothing with that value, and it is lost. A better solution would look like this:
String content = ""
String input = reader.readLine();
while (input != null)
{
content = content + input;
input = reader.readLine();
}
This avoids the problem of reading and then throwing away every other line by storing the line in a variable and checking the variable for null instead.
Each time you call readLine() it reads the next line. The statement
while (reader.readLine() != null)
reads a line but does not do anything with it. What you want is
String line;
StringBuilder buf;
while ( (line = reader.readLine()) != null)
{
buf.append(line);
}
content = buf.toString();
Using a StringBuilder is much better as it avoids reallocating and copying the entire string each time you append.

Read all lines with BufferedReader

I want to type a multiple line text into the console using a BufferedReader and when I hit "Enter" to find the sum of the length of the whole text. The problem is that it seems I'm getting into an infinite loop and when I press "Enter" the program does not come to an end. My code is below:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line!=null){
length = length + line.length();
line= buffer.readLine();
}
Could you please tell me what I'm doing wrong?
One line of code using Java 8:
line = buffer.lines().collect(Collectors.joining());
The idiomatic way to read all of the lines is while ((line = buffer.readLine()) != null). Also, I would suggest a try-with-resources statement. Something like
try (InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream)) {
long length = 0;
String line;
while ((line = buffer.readLine()) != null) {
length += line.length();
}
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
If you want to end the loop when you receive an empty line, add a test for that in the while loop
while ((line = buffer.readLine()) != null) {
if (line.isEmpty()) {
break;
}
length += line.length();
}
JLS-14.15. The break Statement says
A break statement transfers control out of an enclosing statement.
line will not be null when you press enter; it will be an empty string.
Take note of what the BufferedReader JavaDoc says about readLine():
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
And readLine() returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
So when you press [Enter], you are giving the BufferedReader a new line containing only \n, \r, or \r\n. This means that readLine() will return an empty string.
So try something like this instead:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while( (line != null) && (!line.isEmpty()) ){
length = length + line.length();
line = buffer.readLine();
}
When you only press Enter the return from buffer.readLine(); isn't null it is an empty String.
Therefore you should change line != null to !line.equals("") (You could also change it to line.length() > 0)
Now your code will look something like this:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line = buffer.readLine();
while (!line.equals("")){
length = length + line.length();
line = buffer.readLine();
}
This should solve your problem. Hope this helped! :)
Since Java 8 you can use BufferedReader#lines method directly on buffered reader.
try (InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(in)) {
final int length = buffer.lines().mapToInt(String::length).sum();
System.out.println("Read length: " + length);
} catch (Exception e) {
e.printStackTrace();
}
Snarky answer: what you're doing wrong is only creating 2 objects in Java to do something... if you search, you can probably find a few more classes that extend BufferedReader or ExtendedBufferReader etc., and then it can be real Enterprise Java.
Now that i've gotten that out of my system: more useful answer. System.in is closed when you input EOF, which is Control-D under Linux and I think MacOS, and I think Control-Z plus enter under Windows. If you want to check for enter (or more specifically, two enters... one to finish the last line and one to indicate that you're done, which is essentially how http handles determining when the http headers are finished and it's time for the http body, then #dbank 's solution should be a viable option with a minor fix I'm going to try to make to move the ! inside the while predicate instead of !while.
(Edit #2: realized readLine strips the newline, so an empty line would "" instead of the newline, so now my code devolves to another answer with the EOF bit as an answer instead of comment)
Edit... that's weird, #dbank had answered while I was typing my answer, and I would have stopped had I not though mentioning the EOF alternative. To repeat his code from memory with the edit I was going to make:
InputStreamReader instream = new InputStreamReader(System.in);
BufferedReader buffer = new BufferedReader(instream);
line= buffer.readLine();
while (line != null && !line.equals("")){
length = length + line.length();
line= buffer.readLine();
}
Put every lines into String[] array. and second method get the number of lines contains in text file. I hope this might be useful to anyone..
public static void main(String... args) throws IOException {
String[] data = getLines();
for(String v : data) {
out.println(v);
}
}
public static String[] getLines() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
String[] data = new String[getLinesLength()];
int i = 0;
while(line != null) {
data[i] = line;
line = bufferReader.readLine();
i++;
}
bufferReader.close();
return data;
}
public static int getLinesLength() throws IOException {
BufferedReader bufferReader = new BufferedReader(new FileReader("C:\\testing.txt"));
String line = bufferReader.readLine();
int size = 0;
while(line != null) {
size += 1;
line = bufferReader.readLine();
}
bufferReader.close();
return size;
}
Good example from #Russel Yang (https://stackoverflow.com/a/40412945/11079418).
Use this code, to add also a new line character after each line.
String lines = bufferedReader.lines().map(line -> line + "\n").collect(Collectors.joining());

Buffered Reader find specific line separator char then read that line

My program needs to read from a multi-lined .ini file, I've got it to the point it reads every line that start with a # and prints it. But i only want to to record the value after the = sign. here's what the file should look like:
#music=true
#Volume=100
#Full-Screen=false
#Update=true
this is what i want it to print:
true
100
false
true
this is my code i'm currently using:
#SuppressWarnings("resource")
public void getSettings() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("FileIO Plug-Ins/Game/game.ini")));
String input = "";
String output = "";
while ((input = br.readLine()) != null) {
String temp = input.trim();
temp = temp.replaceAll("#", "");
temp = temp.replaceAll("[*=]", "");
output += temp + "\n";
}
System.out.println(output);
}catch (IOException ex) {}
}
I'm not sure if replaceAll("[*=]", ""); truly means anything at all or if it's just searching for all for of those chars. Any help is appreciated!
Try following:
if (temp.startsWith("#")){
String[] splitted = temp.split("=");
output += splitted[1] + "\n";
}
Explanation:
To process lines only starting with desired character use String#startsWith method. When you have string to extract values from, String#split will split given text with character you give as method argument. So in your case, text before = character will be in array at position 0, text you want to print will be at position 1.
Also note, that if your file contains many lines starting with #, it should be wise not to concatenate strings together, but use StringBuilder / StringBuffer to add strings together.
Hope it helps.
Better use a StringBuffer instead of using += with a String as shown below. Also, avoid declaring variables inside loop. Please see how I've done it outside the loop. It's the best practice as far as I know.
StringBuffer outputBuffer = new StringBuffer();
String[] fields;
String temp;
while((input = br.readLine()) != null)
{
temp = input.trim();
if(temp.startsWith("#"))
{
fields = temp.split("=");
outputBuffer.append(fields[1] + "\n");
}
}

How to read a String (file) to array in java

Suppose there is a file named as SUN.txt
File contains : a,b,dd,ss,
I want to make dynamic array depending upon the number of attributes in file.
If ther is a char after comma then array will be of 0-4 i.e of length 5.
In the above mentioned case there is no Char which returns 0-3 Array of length 4. I want to read the NULL after comma too.
How do i do that?
Sundhas
You should think about
Reading the file into a String
Splitting the file by separator ','
Using a list for adding the characters and convert the list to an array, when the list is filled
As Markus said, you want to do something like this..
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//The StringBuffer will be used to create a string if your file has multiple lines
StringBuffer sb = new StringBuffer();
String line;
while((line = reader.readLine())!= null)
{
sb.append(line);
}
//We now split the line on the "," to get a string array of the values
String [] store = sb.toString().split(",");
I do not quite understand why you would want the NULL after the comma? I am assuming that you mean after the last comma you would like that to be null in your array? I do not quite see the point in that but that is not what the question is.
If that is the case you wont read in a NULL, if after the comma there was a space, you could read that in.
If you would like a NULL you would have to add it in yourself at the end so you could do something like
//Create a buffred reader so that you can read in the file
BufferedReader reader = new BufferedReader(new FileReader(new File(
"\\SUN.txt")));
//Use an arraylist to store the values including nulls
ArrayList<String> store = new ArrayList<String>();
String line;
while((line = reader.readLine())!= null)
{
String [] splitLine = line.split(",");
for(String x : splitLine)
{
store.add(line);
}
//This tests to see if the last character of the line is , and will add a null into the array list
if(line.endsWith(","))
store.add(null);
}
String [] storeWithNull = store.toArray();
Well if you want want to simply open the file and store the content in a array of string then
1) open the file into a string
2) split the string using a regex "," http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)
but I'm curious why you can't use a String file directly ?
For your datatructure, use a list of arrays. Each list entry is a line of your textfile, each entry is an array that holds the comma separated values:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
data.add(line.split(","));
line = readNextLine();
}
(assuming, your file contains 1..n lines of comma separated values)
You may want to have it like this:
"a,b,c,d," -> {"a", "b", "c", "d", null}
Here's a suggestion how to solve that problem:
List<String[]> data = new ArrayList<String[]>();
String line = readNextLine(); // custom method, to be implemented
while (line != null) {
String[] values = new String[5];
String[] pieces = line.split(",");
for (int i = 0; i<pieces.length; i++)
values[i] = pieces[i];
data.add(values);
line = readNextLine();
}
its seems like a CSV file something like this will work assuming it has 5 lines and 5 values
String [][] value = new String [5][5];
File file = new File("SUN.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
int row = 0;
int col = 0;
while((line = br.readLine()) != null ){
StringTokenizer s = new StringTokenizer(line,",");
while (s.hasMoreTokens()){
value[row][col] = s.nextToken();
col++;
}
col = 0;
row++;
}
i havent tested this code
Read the file, using BufferedReader, one line at the time.
Use split(",", -1) to convert to an array of String[] including also empty strings beyond the last comma as part of your array.
Load the String[] parts into a List.

Categories