這裏是我的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());
}
}
下面是我在對話框中的 「Load按鈕」 的代碼:
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();
}
}
而「按鈕保存」代碼:
JFileChooser fc = new JFileChooser();
int choice = fc.showSaveDialog(null);
if (choice == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getAbsolutePath();
txaConversation.setText(filename);
writeToFile(filename);
}
當我保存並從我的電腦打開文本文件時,我可以看到文本。但是當我使用我的程序加載它時,它向我顯示文件路徑。
'writeToFile(filename);'這一行將文件名寫入文件,所以它是有意義的,這就是文件將包含的內容 –