• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading multiple lines in a file to a single string.  RSS feed

 
Nathan Heimdall
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a the following file (Input.txt):

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB

I need to store the data separated by an empty line into two separate strings.

i.e
num1="AAAAAAAAAAAAAAAAA.....AAA"
num2="BBBBBBBBBBBBBBBBB......BBB"

I am using the following code :

in = new BufferedReader(new FileReader("Input.txt"));
num1=in.readLine();
num2=in.readLine();

which does not work as num1= (first line of A's )AAAAAAAA... and num2=(second line of A's)AAAA...

How can read the data into a string until I encounter an empty line?

Thanks,
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using that same code, what does BufferedReader.readLine() return when it encounters an empty line?
 
Nathan Heimdall
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BufferedReader.readLine() reads only a single line at a time irrespective of the spacing.
I still cant figure out how I can use the its value to read read two strings in a file separated by an empty line and store in separate strings.
How can I use the return the value in this case?.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume you have read the java.io.BufferedReader#readLine() documentation. So when you have no lines left you get null, when you have a line with something in, you get a String, and when you have an empty line you get . . .

Once you work out the answer to that, you can use the methods of the String class to test whether you have encountered an empty line.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are probably best using a StringBuilder to join several Strings together.
 
Nathan Heimdall
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!