【发布时间】:2018-09-24 17:11:47
【问题描述】:
我知道我没有正确地做某事。我知道该文件需要可序列化才能读取文本文件。
我在主类上实现了 Serializable 。但是我的 readText 和 writeText 没有转换。
当我阅读和写出文件不是文本时,什么都没有。
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
【问题讨论】:
-
您的 while 循环在 catch 块内...
-
不清楚您要做什么。将文件逐行读入列表?这里已经回答了stackoverflow.com/q/5343689/2308683
-
你需要在
while循环之前关闭IOException e1catch。 -
它是加密和解密文件的大型程序的一部分。您读入文本文档,打印出来,加密和打印,将加密文件保存到文本文件,从内存中清除它,读入加密文本文件,解密文件,将解密文件写出到控制台然后就完成了。这是一个 ArrayList,我必须打开一个对话框来引入一个文本文件(原始文件和加密版本)。这说明清楚了吗?