2014-12-03 36 views
-1

我的代碼的目的是最終要求用戶輸入文件名,並且如果它已經是當前目錄中的文件,那麼會打印一條錯誤消息,如果它不是,那麼它是應該創建文件並將行寫入新創建的文件,直到用戶輸入結束。程序應該繼續這樣做的最後一件事是,直到用戶進入退出程序。所以用簡單的術語來說,用戶輸入一個文件名(它不是文件),它們被提示輸入一行然後另一行,用戶輸入end,然後提示用戶再次輸入一個文件名,並輸入exit和程序停止。然而,我將發佈的代碼是創建文件,但實際上沒有寫入它,幫助?我在java的eclipse的方式字符串寫入器不寫入文件

import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.io.UnsupportedEncodingException; 
import java.util.Scanner; 

public class PrintWriter { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    Scanner input = new Scanner(System.in); 

    PrintWriter writer = null; 
    // Initializes the printwriter as writer 

try 
    { 
     writer = new PrintWriter("printwriter3.txt", "UTF-8"); 
     // will write in the UTF-8 language to a file named printwriter.txt 

     boolean exit = false; 
     while (exit == false) 
     { 
      String user = input.nextLine(); 
      if (user.equals("end")) 
      { 
       exit = true; 
      } 
      else 
      { 
       writer.println(user); 
      } 

     } 
    } 
    catch (FileNotFoundException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("File not found"); 
     // if the file is not found then this error message is printed 
    } 
    catch (UnsupportedEncodingException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     System.out.println("The encoding type is not supported"); 
     // if the encoding type in this case UTF-8 is not supported an error message is printed 
    } 
+3

當你完成它的時候,你關閉了作家嗎? – Compass 2014-12-03 17:45:11

+0

你沒有關閉你的作家。另外,Java 7還有一個帶有資源的Try/Catch塊的實現。以下是參考資料:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。 此方法負責關閉。 – 2014-12-03 17:47:52

回答

1

你已經忘記關閉作家。 如果您想確保程序仍在運行時可以看到更改,則必須在打印後進行刷新。

 writer = new PrintWriter("printwriter3.txt", "UTF-8"); 
     // will write in the UTF-8 language to a file named printwriter.txt 

     boolean exit = false; 
     while (exit == false) 
     { 
      String user = input.nextLine(); 
      if (user.equals("end")) 
      { 
       exit = true; 
      } 
      else 
      { 
       writer.println(user); 
       writer.flush(); 
      } 

     } 
     writer.close(); 
0

我可以在這裏看到兩個問題。一個你沒有關閉作家,第二,你有相同的類名稱作爲導入類(PrintWriter)。所以當你聲明一個Printwriter的實例時,它會創建你的類的實例而不是java.io.Printwriter。