-
Notifications
You must be signed in to change notification settings - Fork 4
Java Text IO
Anthony Christe edited this page Nov 8, 2013
·
1 revision
- Possible to pass an array of Strings into main method of java program
public class ArgsTest {
public static void main(String[] args) {
for(String arg : args) {
System.out.println(arg);
}
}
}- Then we can run the above with:
javac ArgsTest.java
java ArgsTest Each one of these words will become an argument
Each
one
of
these
words
will
become
an
argument
- More often then not, we use these command line arguments to change how a program runs at runtime
public class ArgsTest {
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Invalid number of parameters");
System.out.println("Usage: java ArgsTest file_path");
System.exit(1);
}
String filePath = args[0];
...
}
}- Read/write text files
- Read/write binary files
- Read/write Java objects
- Java provides many classes for handling IO, though we're only going to look at a few
- Easiest to accomplish using Scanner class for small files
Scanner in = null;
File textFile = new File("/path/to/file");
try {
in = new Scanner(textFile);
while(in.hasNextLine()) {
System.out.println(in.nextLine());
}
}
catch (FileNotFoundException e) {
System.err.format("File %s not found\n", textFile);
e.printStackTrace();
}- For large files, use BufferedReader in combination with FileReader
- Buffering the data means less accesses to disk (read or write in bulk)
File textFile = new File("/path/to/file");
BufferedReader bufferedReader = null;
String line;
try {
bufferedReader = new BufferedReader(new FileReader(textFile));
line = bufferedReader.readLine();
while(line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
}
catch (FileNotFoundException e) {
System.err.format("File %s not found\n", textFile);
e.printStackTrace();
}
catch (IOException e) {
System.err.format("Problem reading file %s\n", textFile);
e.printStackTrace();
}- Use FileWriter and BufferedWriter
- Take special care if intention is to append to file rather than overwrite
File textFile = new File("/home/anthony/scrap/test2.txt");
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(textFile));
for(int i = 0; i < 10; i++) {
bufferedWriter.write(String.format("Hello, World! %d\n", i));
}
bufferedWriter.close();
}
catch (IOException e) {
System.err.format("Problem writing to file %s\n", textFile);
e.printStackTrace();
}- Download the files located at https://github.com/anthonyjchriste/ics211f13/tree/master/src/io
- Complete readFile which should return a list of lines of the text file
- Complete writeFile which writes a list of lines to a text file
- Complete the main method so that the read in file is the first command line parameter and the file being written to comes in as the second command line parameter