File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "FileInputStream to a String" Watch "FileInputStream to a String" New topic
Author

FileInputStream to a String

Raja Sam
Greenhorn

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;

java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);

int i;

while ((i=fileInputStream.read()) != -1)
{

System.out.write(i);
}

fileInputStream.close();
Ramesh Pramuditha Rathnayake
Ranch Hand

Joined: Oct 31, 2012
Posts: 175
    
    1

Try this..




Ramesh-X
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14435
    
  23

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 8 API documentation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: FileInputStream to a String