Read/Write Files

To read in from and file and also output to a file, java uses streams to “talk” to the files. These streams allow for communicating with different stream conversion tools, the object tool within this tutorial is the DataInputStream which “talks” to the FileInputStream.

I have attached the code within a zip file with the required input file as well.

Below is the code

importjava.io.*;class javareadfile
{publicstaticvoid main(String args[]){String fileName ="country.txt";//input fileString outFileName ="sqljavacountry.txt";//output filetry{// file input stream, basically a pointer to the stream of the input fileFileInputStream fStream =newFileInputStream(fileName);// file output stream, basically a pointer to the stream for outputing dataFileOutputStream fOutStream =newFileOutputStream(outFileName);// the input/output data streams that connect to the above streamsDataInputStream dInput =newDataInputStream(fStream);DataOutputStream dOutput =newDataOutputStream(fOutStream);// whilst there is data available in the input streamwhile(dInput.available()!=0){String in = dInput.readLine();// read a line from the input file// output a stream of data to the output file
dOutput.writeBytes("insert into country(place) values (\""+in+"\");\n");}//close the two files.
dInput.close();
dOutput.close();}catch(Exception e)// incase of any errors{System.err.println("There was a error : "+ e.toString());}}}

If you save this as javareadfile.java and also create a countrys.txt file with what ever text you like, e.g.

United Kingdom
France
Germany
United States
etc.

Once you have compiled the program (javac -deprecation javareadfile.java, may have to use -deprecation if using java virtual machine 1.5 over 1.4) and execute the program (java javareadfile), it will look for the file countrys.txt within the same directory as the program executable and also create outcountrys.txt within the same directory (it will write over the file if there is one present). Then within the while loop it will read the input file line by line and output to the screen what has been read and also output to the output file.

Of course to finish off to close down the files and return back to the console.

Thanks for the article.
I thought I would leave you a comment, because there are a few articles ahead of you here and they arent as well written as yours.
I am taking Java 2 this semester and I forgot how to do the file input, so this is a great review.
Thanks!