Key Ideas
[Part 7 of 11]
There are two key ideas in this part:
- Files are represented by
java.io.File
objects. One common way to get a path for these is using ajava.io.FileDialog
:FileDialog fd = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
fd.setVisible(true);
File f = null;
if((fd.getDirectory() != null)||( fd.getFile() != null)) {
f = new File(fd.getDirectory() + fd.getFile());
}
- The second is that if we are reading or writing text files, we do this using streams, but
wrapped in buffers. If you use a stream, it is always polite to close it after use:
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("a:/data.txt")));
} catch (FileNotFoundException fnfe) {
return null;
}
try {
return br.readLine();
} catch(IOException ioe) {
throw ioe;
} finally {
try {
br.close();
} catch (IOException ioe) {
return null;
}
}
Here's some code which uses these ideas. Note that it sticks with printStackTrace
just for clarity.
double[][] data = null;
BufferedReader br = null;
File f = new File("c:/in.txt");
// Count the number of lines.
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int lines = -1;
String textIn = " ";
String[] file = null;
try {
while (textIn != null) {
textIn = br.readLine();
lines++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
// Reopen the file at the top and read the
// file into a String array of the right size.
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
file = new String[lines];
try {
for (int i = 0; i < lines; i++) {
file[i] = br.readLine();
}
} catch (IOException e) {
e2.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
// Convert each line into an array of double data.
data = new double [lines][];
for (int i = 0; i < lines; i++) {
StringTokenizer st = new StringTokenizer(file[i],", ");
data[i] = new double[st.countTokens()];
int j = 0;
while (st.hasMoreTokens()) {
data[i][j] = Double.parseDouble(st.nextToken());
j++;
}
}
// Check data.
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print (data[i][j] + ", ");
data[i][j]++;
}
System.out.println("");
}
// Write data. Note we're going to change the file from
// comma separated variables (CSV) to space separated.
BufferedWriter bw = null;
try {
bw = new BufferedWriter (new FileWriter(new File("c:/out.txt")));
} catch (IOException e) {
e.printStackTrace();
}
String tempStr = "";
try{
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
tempStr = String.valueOf(data[i][j]);
System.out.print(tempStr + ", ");
bw.write(tempStr + ", ");
}
System.out.println("");
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}