Java: Summary: I/O
This needs a lot of work!!!!!!!!!!!
Related classes: File, BufferedReader, ....
| Some System methods are relevant to I/O |
| String System.getProperty("user.dir") |
Returns the path to the current directory (ie, the value of "."). |
File Methods
These are some of the most common File methods.
In all of these prototypes,
i and
j are int,
s and
t are Strings,
and
c is a char.
| boolean | f.exists() |
true if file exists. |
| boolean | f.isFile() |
true if its a file. |
| boolean | f.isDirectory() |
true if its a directory. |
| String | f.getName() |
returns name of file/directory. |
| String | f.getPath() |
returns path of file/directory. |
| File[] | File.listRoots() |
[Java 2] list of file system roots, eg, A:, C:, .... |
BufferedReader/BufferedWriter Methods
java.io.BufferedReader and java.io.BufferedWriter are
used to read/write Strings from/to text files.
| String | br.readLine() |
Returns next input line without newline char(s) or null if no more input.
May throw IOException. |
| String | br.close() |
Should close when finished reading. |
| void | bw.writeLine(s) |
Writes s to file without newline char(s).
May throw IOException. |
| String | bw.close() |
MUST close when finished writing. |
Example
// Example reads from from one file and writes to another.
// Assume inFile and outFile are Strings with path/file names.
try {
BufferedReader bufReader = new BufferedReader(new FileReader(inFile));
BufferedWriter bufWriter = new BufferedWriter(new FileWriter(outFile));
String line = null;
while ((line=bufReader.readLine()) != null){
bufWriter.write(line);
bufWriter.newLine(); // adds newline character(s)
}
bufReader.close();
bufWriter.close();
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
Current Comments
0 comments so far (post your own) View All Comments Latest 10 Comments: