2010-05-04 76 views
1

如何修改此運行方法,以便不僅可以在輸出窗口中打印srting,還可以在項目目錄中寫入例如outfile.txt的文件。另外,每個字符串應該位於文件的單獨一行中。用java寫入文件

所以我已創建項目目錄中的文件名爲outfile.txt

一個瞬間的代碼是關於窗口打印正常,但在文本文件中

這裏不打印是代碼#

public void run() throws IOException 
{ 
    Scanner sc = new Scanner(System.in); 
    boolean cont = true; 
    while (cont) { 
     System.out.println("Enter text"); 
     String s = sc.nextLine(); 
     if ("*".equals(s)) { 
      cont = false; 
     } else { 
      String result = shorthand(s); 
      System.out.println(result); 
      PrintWriter pw = new PrintWriter("outfile.txt"); 
      pw.println(result); 
     } 
    } 
} 

回答

0

你不應該在java.io.File東西使用相對路徑。它們將與當前的工作目錄相關,而這又取決於如何啓動Java應用程序。這可能不是您期望的項目目錄。您應該始終在java.io.File中使用絕對路徑。例如。 c:/path/to/outfile.txt

要了解它是目前實際上被寫入,這樣做:

File file = new File("outfile.txt"); 
System.out.println(file.getAbsolutePath()); 

再次,從來沒有使用相對路徑。始終使用絕對路徑。否則就把它放在類路徑中,然後使用ClassLoader#getResource(),然後URL#toURI(),然後使用new File(uri)

事實上,關閉流。它會隱式地將數據緩衝區刷新到資源。

+0

PrintWriter out = new PrintWriter(new FileWriter(「outfilename」)); out.write(結果); out.close();但似乎仍然沒有工作,我已經嘗試了文件的位置的完整路徑。任何想法 – luvthug 2010-05-04 13:34:50

6

一旦你寫完了,你需要關閉打開的文件:

pw.Close(); 
+0

PrintWriter out = new PrintWriter(new FileWriter(「outfilename」)); out.write(結果); out.close(); 但似乎仍然沒有工作,我已經試過文件的位置的完整路徑。任何想法 – luvthug 2010-05-04 13:34:05

+0

你看到了什麼?我會得到你只會看到_last_行,因爲每次通過循環時都覆蓋文件。 – Oded 2010-05-04 13:36:02

+0

沒有文本文件是空的什麼都沒有被寫入初始化 – luvthug 2010-05-04 13:38:29

1

只要看一看exampledot

+3

我們喜歡在這裏看到_answers_,而不是鏈接。 – Oded 2010-05-04 13:18:18

+1

PrintWriter out = new PrintWriter(new FileWriter(「outfilename」)); out.write(結果); out.close();但似乎仍然沒有工作,我已經嘗試了文件的位置的完整路徑。任何想法 – luvthug 2010-05-04 13:34:33

0

您正在創建一個新的printwriter每次。考慮在循環之前進行,因此

PrintWriter pw = new... 
while(cond) { 
    ... 
    pw.println(...); 
    pw.flush(); // do this too, it does the actual writing 
} 
pw.close(); 
+0

沒有運氣。基本上,問題是詢問以下內容: 修改run方法,以便現在壓縮的字符串不僅被打印在輸出窗口中,而且還被寫入項目目錄中名爲outfile.txt的文件。每個壓縮字符串應該位於文件的單獨一行中。當*輸入代碼應終止,但*不應在文件 – luvthug 2010-05-04 17:17:28

+0

在這裏,在寫這就是我得到的,當我複製你的代碼,使我改變 - >代碼http://pastebin.com/LmP55aZU 這是否不適合你? – corsiKa 2010-05-05 13:09:59