我的代碼的目的是最終要求用戶輸入文件名,並且如果它已經是當前目錄中的文件,那麼會打印一條錯誤消息,如果它不是,那麼它是應該創建文件並將行寫入新創建的文件,直到用戶輸入結束。程序應該繼續這樣做的最後一件事是,直到用戶進入退出程序。所以用簡單的術語來說,用戶輸入一個文件名(它不是文件),它們被提示輸入一行然後另一行,用戶輸入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
}
當你完成它的時候,你關閉了作家嗎? – Compass 2014-12-03 17:45:11
你沒有關閉你的作家。另外,Java 7還有一個帶有資源的Try/Catch塊的實現。以下是參考資料:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。 此方法負責關閉。 – 2014-12-03 17:47:52