2 回答

TA貢獻1833條經驗 獲得超4個贊
在你的程序中,你似乎已經扔掉了所有東西并希望它能起作用。要找出應該使用哪個類,您應該在 Java 版本的 Javadoc 中搜索它。?
打印作家:
將對象的格式化表示打印到文本輸出流。此類實現了 PrintStream 中的所有打印方法。它不包含寫入原始字節的方法,程序應使用未編碼的字節流。
文件編寫器:
使用默認緩沖區大小將文本寫入字符文件。從字符到字節的編碼使用指定的字符集或平臺的默認字符集。
掃描儀(文件來源):
構造一個新的 Scanner,它生成從指定文件掃描的值。使用底層平臺的默認字符集將文件中的字節轉換為字符。
現在您可以看到每個課程的用途。PrintWriter 和 FileWriter 都用于寫入文件,但 PrintWriter 提供更多格式選項,而 Scanner(文件源)用于讀取文件而不是寫入文件。
因為 PrintWriter 已經有了答案。我正在使用 FileWriter 編寫此內容。
public static void main(String[] args) throws Exception {
? ? // Create a Scanner object for keyboard input.
? ? Scanner input = new Scanner(System.in);
? ? // You can provide file object or just file name either would work.
? ? // If you are going for file name there is no need to create file object
? ? FileWriter outputfile = new FileWriter("namef.txt");
? ? System.out.print("Enter the number of data (N) you want to store in the file: ");
? ? int N = input.nextInt(); // numbers from the user through keyboard.
? ? System.out.println("Enter " + N + " numbers below: ");
? ? for (int i = 1; i <= N; i++) {
? ? ? ? System.out.print("Enter the number into the file: ");
? ? ? ? // Writing the value that nextInt() returned.
? ? ? ? // Doc: Scans the next token of the input as an int.
? ? ? ? outputfile.write(Integer.toString(input.nextInt()) + "\n");
? ? }
? ? System.out.println("Data entered into the file.");
? ? input.close();
? ? outputfile.close(); // Close the file.
}
輸出:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:?
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
文件:
2
1

TA貢獻1821條經驗 獲得超6個贊
這是您想要實現的目標的一個工作變體:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
對上面的幾點評論:
1)刪除多余的行:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
其實你根本就沒有使用過它們。
2)在PrintWriter我們傳遞File對象,而不是String。
3)在for循環中存在邏輯錯誤 - 在每次迭代中,您應該編寫N而不是用戶在控制臺上輸入的實際數字。
4)另一個錯誤是在最后一行關閉了錯誤的文件。
編輯:根據評論添加。在第 2 點)中,還有一種替代方法 - 您可以跳過創建File對象并String直接將其作為路徑傳遞給甚至不存在的文件PrintWriter,如下所示:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");
添加回答
舉報