这是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.");
}
}
答案 0 :(得分:8)
您正在创建一个PrintWriter
实例,但没有写入任何内容。
也许您打算在for循环中包含outputFile.println(friendName)
?
答案 1 :(得分:0)
尝试
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();
outputFile.println(friendName);
}