Skip to content

Instantly share code, notes, and snippets.

@leonardreidy
Created September 21, 2015 13:52
Show Gist options
  • Save leonardreidy/533ecd0ee3cd69bd87eb to your computer and use it in GitHub Desktop.
Save leonardreidy/533ecd0ee3cd69bd87eb to your computer and use it in GitHub Desktop.
Java class with methods for simplifying file i/o.
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.StringBuffer;
public class FileUtilities
{
private Charset charset;
private StringBuffer stringBffr;
public FileUtilities()
{
charset = Charset.forName("US-ASCII");
stringBffr = new StringBuffer();
}
public static void fileOpen(JComponent j) {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(this);
if ( returnVal == JFileChooser.APPROVE_OPTION ) {
java.io.File file = fc.getSelectedFile();
// Open and read the file to a string buffer
try (BufferedReader reader = Files.newBufferedReader(FileSystems.getDefault().getPath(file.getPath()), charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
stringBffr.append(line+"\n");
}
} catch (IOException iox) {
System.err.format("IOException: %s%n", iox);
}
System.out.println("Opening: " + file.getName());
} else {
System.out.println("Open command cancelled by user.");
}
j.append(stringBffr.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment