This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes FileInputStream to a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "FileInputStream to a String" Watch "FileInputStream to a String" New topic

FileInputStream to a String

Raja Sam

Joined: Jul 08, 2013
Posts: 1
I have the following logic to open a file:

Except what I want to do is not just print the file on the screen, but to take a particular line and store it to a String called test.

For example take line 35 in the text file and store that in the String called test.

Can someone please help me with this ?

// fetch the file
String filename = "companySecret.txt";
String filepath = "C:\\";
String test; fileInputStream = new + filename);

int i;

while (( != -1)


Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 169

Try this..

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114

It looks like you're reading a text file. Especially if you're interested in reading the file line by line, then using a BufferedReader will be easier and faster than reading the file character by character.

Another problem is that you're directly casting bytes read from the file to characters. That only works if the file contains ASCII text (it might fail if the file actually contains text in another character encoding). I won't go into that though, it's a more advanced subject.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
jQuery in Action, 2nd edition
subject: FileInputStream to a String