Wednesday, May 16, 2007

File Input/Output

Here is some Java code that can be re-used so that you don't have to re-type this all the time:

The following code reads a file line by line. It does other cool stuff too.




import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileOutputStream;
import java.io.File;
import java.io.PrintStream;

import javax.swing.JFileChooser;
import javax.swing.ProgressMonitor;
import javax.swing.filechooser.FileSystemView;

public class FileInput {

/**
* @param args
*/
public static void main(String[] args) {

//redirect the output and error stream to a file.
//This is useful when working Swing apps that don't show a console.
try {
System.setOut(new PrintStream(
new FileOutputStream("FileInput_output.txt", false)));
System.setErr(new PrintStream(
new FileOutputStream("FileInput_log.txt", false)));
}
catch( FileNotFoundException fnfe ) {
System.err.println("Error setting output stream to log files");
fnfe.printStackTrace();
}

//add a file chooser to allow choosing a diretory of where a set
//of files to input are
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Specify the location of input files");

//set mode to only view and choose directories
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {

//get all files in the chosen directory
FileSystemView fsv=FileSystemView.getFileSystemView();
File[] files = fsv.getFiles(chooser.getSelectedFile(), true);

try {
//to make it cool, we'll add a progress monitor to show what
//file the system is processing
ProgressMonitor progressBar = new ProgressMonitor(
null,
"FileInput Progress",
"",
0,
files.length);

for(int i=0; i
progressBar.setProgress(i);
progressBar.setNote("Processing file: " +
files[i].getName());

//read the file
BufferedReader in = new BufferedReader(
new FileReader(files[i]));

String line;

while( (line = in.readLine())!= null) {

//Do stuff with each line here

}
in.close();
}

progressBar.close();
}
catch( Exception e ) {
System.err.println(e);
}
}
}
}