At first I though 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 double. However when I tried to use the same class file for another lesson (display it in frame I created), I keep getting 0.0 as the value of the output .txt file. Below is the code for my read and write class:
Expand|Select|Wrap|Line Numbers
- 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();
- }
- }
- }