I am doing this homework where I am supposed to read a .txt file filled with integers into a double array, and then write this double array into another .txt file.
At first I thought everything was working as I was able to read the file and display it out as an image, and then save it into a .txt file as doubles. However, when I tried to use the same class file for another lesson (display it in frame I created), I kept getting 0.0 as the value of the output .txt file. Below is the code for my read and write class:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class IO {
FileDialog fd;
public double[][] readData() {
fd = new FileDialog(new Frame(), "Open Files", FileDialog.LOAD);
fd.setVisible(true);
File f = null;
if ((fd.getDirectory() != null)||( fd.getFile() != null)) {
f = new File(fd.getDirectory() + fd.getFile());
}
FileReader fr = null;
try {
fr = new FileReader (f);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
BufferedReader br = new BufferedReader(fr);
int lines = -1;
String textIn = " ";
String[] file = null;
try {
while (textIn != null) {
textIn = br.readLine();
lines++;
}
file = new String[lines];
fr = new FileReader (f);
br = new BufferedReader(fr);
for (int i = 0; i < lines; i++) {
file[i] = br.readLine();
}
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
double[][] 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++;
}
}
return data;
}
public void writeData(double[][] dataIn) {
fd = new FileDialog(new Frame(), "Save Files", FileDialog.SAVE);
fd.setVisible(true);
File f = null;
if ((fd.getDirectory() != null)||( fd.getFile() != null)) {
f = new File(fd.getDirectory() + fd.getFile());
}
FileWriter fw = null;
try {
fw = new FileWriter (f, true);
} catch (IOException ioe) {
ioe.printStackTrace();
}
BufferedWriter bw = new BufferedWriter (fw);
String tempStr = "";
try {
for (int i = 0; i < dataIn.length; i++) {
for (int j = 0; j < dataIn[i].length; j++) {
tempStr = String.valueOf(dataIn[i][j]);
bw.write(tempStr);
}
bw.newLine();
}
bw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
The txt file I am trying to read have 300 rows and column, of which not all column are filled to full with int number. I could get the input txt to be Display but could not save it back as a txt file with the same values but in double instead of int.
Could someone help me out here please?
I’m not sure I understand your complete problem, but you have at least the problem that you forget to add a comma after each number when you write to the file. Since
readDatauses commas to separate numbers, files produced by your program cannot be read by it. Simply changeto
(removed the intermediate
tempStrsince it is unnecessary as your code is now).