Java程序不会输出到文件
这是Uni的一个非常基本的程序,它将用户数据写入文件。我已经清楚地遵循了说明,但它似乎没有将数据输出到文件中。它所做的只是创建一个空文件。如果这有什么不同的话,我正在使用Ubuntu
import java.util.Scanner;
import java.io.*;
/**
This program writes data to a file.
*/
public class FileWriteDemo
{
public static void main(String[] args) throws IOException
{
String fileName; // File name
String friendName; // Friend's name
int numFriends; // Number of friends
// Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get the number of friends
System.out.print("How many friends do you have? ");
numFriends = keyboard.nextInt();
// Consume the remaining new line character
keyboard.nextLine();
// Get the file name
System.out.print("Enter the filename: ");
fileName = keyboard.nextLine();
// Open the file
PrintWriter outputFile = new PrintWriter(fileName);
// Get data and write it to a file.
for (int i = 1; i <= numFriends; i++)
{
// Get the name of a friend
System.out.print("Enter the name of friends " +
"number " + i + ": ");
friendName = keyboard.nextLine();
}
// Close the file
outputFile.close();
System.out.println("Data written to the file.");
}
}
# 1 楼答案
您正在创建一个
PrintWriter
实例,但没有写入任何内容也许你想在for循环中包含
outputFile.println(friendName)
# 2 楼答案
试试看