views:

557

answers:

3

I'm coming from a C++ background, so be kind on my n00bish queries...

I'd like to read data from an input file and store it in a stringstream. I can accomplish this in an easy way in C++ using stringstreams. I'm a bit lost trying to do the same in Java.

Following is a crude code/way I've developed where I'm storing the data read line-by-line in a string array. I need to use a string stream to capture my data into (rather than use a string array).. Any help?

    char dataCharArray[] = new char[2];
    int marker=0;
    String inputLine;
    String temp_to_write_data[] = new String[100];

    // Now, read from output_x into stringstream

    FileInputStream fstream = new FileInputStream("output_" + dataCharArray[0]);

    // Convert our input stream to a BufferedReader
    BufferedReader in = new BufferedReader (new InputStreamReader(fstream));

    // Continue to read lines while there are still some left to read
    while ((inputLine = in.readLine()) != null )
    {
        // Print file line to screen
        // System.out.println (inputLine);
        temp_to_write_data[marker] = inputLine;
        marker++;
    }

EDIT:

I think what I really wanted was a StringBuffer. I need to read data from a file (into a StringBuffer, probably) and write/transfer all the data back to another file.

A: 

StringBuffer is one answer, but if you're just writing it to another file, then you can just open an OutputStream and write it directly out to the other file. Holding a whole file in memory is probably not a good idea.

Kylar
A: 

In you simply want to read a file and write another one:

BufferedInputStream in = new BufferedInputStream( new FileInputStream( "in.txt" ) );
BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream( "out.txt" ) );
int b;
while ( (b = in.read()) != -1 ) {
    out.write( b );
}

If you want to read a file into a string:

StringWriter out = new StringWriter();
BufferedReader in = new BufferedReader( new FileReader( "in.txt" ) );
int c;
while ( (c = in.read()) != -1 ) {
    out.write( c );
}
StringBuffer buf = out.getBuffer();

This can be made more efficient if you read using byte arrays. But I recommend that you use the excellent apache common-io. IOUtils (http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html) will do the loop for you.

Also, you should remember to close the streams.

Manuel Darveau
+1  A: 

In Java, first preference should always be given to buying code from the library houses

http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html

In short

FileUtils.readFileToString(File file) is what you need.
Calm Storm