permaculture playing cards
The moose likes Beginning Java and the fly likes Convert file to a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert file to a String" Watch "Convert file to a String" New topic

Convert file to a String

John Landon
Ranch Hand

Joined: Sep 25, 2008
Posts: 228
Hi I have a file on my hard drive (it's regular character file).
I need to return it's representation as a String.

Ravikanth kolli
Ranch Hand

Joined: Feb 10, 2008
Posts: 179

you can probably try using the fileReader
[ December 09, 2008: Message edited by: Ravikanth kolli ]

Kanna Srini

Joined: Dec 09, 2008
Posts: 2

public class FileReader {

public String getFileAsString(File file){ FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

while (dis.available() != 0) {
sb.append( dis.readLine() +"\n");

} catch (FileNotFoundException e) {
} catch (IOException e) {
return sb.toString();
public static void main(String[] args) {

File file = new File("C:/setup.log");
FileReader fd = new FileReader();
String s = fd.getFileAsString(file);

method getFileAsString get you the file as a single string. This program should be further improved by avoid using depricated APIs (DataInputStream)

I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: Convert file to a String
It's not a secret anymore!