下面是我的readFromFile代码:
private void readFromFile(String file) {
String string = "";
//reading
try{
InputStream ips=new FileInputStream(filename);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null){
string += line + "n";
}
br.close();
txaConversation.setText(string);
}
catch (Exception e){
System.out.println(e.toString());
}
}
下面是我的对话框中"加载按钮"的代码:
JFileChooser fc = new JFileChooser();
int choice = fc.showOpenDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
readFromFile(filename);
txaConversation.setText(filename);
}
如果你会问,这里是writeToFile代码:
private void writeToFile(String filename) {
try {
String content = txaConversation.getText();
File file = new File(filename);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
和"button save"代码:
JFileChooser fc = new JFileChooser();
int choice = fc.showSaveDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
txaConversation.setText(filename);
writeToFile(filename);
}
当我保存它并从我的电脑上打开文本文件时,我可以看到文本。但是当我使用我的程序加载它时,它显示了文件路径
应该是ips.readLine()
而不是br.readLine()
int line;
while ((line=ips.read())!=-1){
string += (char)line ;
}
不需要
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
您的意思是在您的UI中显示文件的名称,而不是内容?
JFileChooser fc = new JFileChooser();
int choice = fc.showOpenDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
readFromFile(filename); // This reads the file content, but does not store it
txaConversation.setText(filename); // Previous content of filename variable is the absolute path
}
将最后两行更改为以下内容,您将显示文件
的内容filename = readFromFile(filename);
txaConversation.setText(filename);
并将readFromFile方法更改为以下
private String readFromFile(String file) {
String string = "";
//reading
try{
InputStream ips=new FileInputStream(filename);
InputStreamReader ipsr=new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null){
string += line + "n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
return string;
}
我还强烈建议您查看finally块中的资源处理