[英]Read file and save as double array, then write it as new file
我正在做这个作业,我应该将填充有整数的.txt
文件读入double
精度数组,然后将此双.txt
数组写入另一个.txt
文件。
起初,我认为一切正常,因为我能够读取文件并将其显示为图像,然后将其保存为double
的.txt
文件。 但是,当我尝试将同一类文件用于另一堂课(在创建的帧中显示)时,我一直得到0.0
作为输出.txt
文件的值。 以下是我的读写类的代码:
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();
}
}
}
我尝试读取的txt文件有300行和列,其中不是所有的列都用int号填满。 我可以将输入txt显示为,但无法将其另存为具有相同值但以double而不是int的txt文件。
有人可以帮我吗?
我不确定我是否理解您的完整问题,但是至少您有一个问题,当您写入文件时,您忘记了在每个数字后添加逗号。 由于readData
使用逗号分隔数字,因此程序无法读取程序生成的文件。 只需更改
for (int j = 0; j < dataIn[i].length; j++) {
tempStr = String.valueOf(dataIn[i][j]);
bw.write(tempStr);
至
for (int j = 0; j < dataIn[i].length; j++) {
bw.write(String.valueOf(dataIn[i][j]) + ",");
(删除了中间的tempStr
因为现在不需要它了,因为它是不必要的)。
我认为我已经设法进行了排序,不确定这是否正确。 以下是我在try catch循环之前添加的内容:
BufferedWriter bw = new BufferedWriter (fw);
dataIn = getData(dataIn);
try {
我在Class中创建了一个getData(double [] [] data)方法,因此现在可以读取数据了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.