Java程序不会输出到文件

Swi*_*ick 2 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.");
    }

}
Run Code Online (Sandbox Code Playgroud)

Bal*_*a R 8

您正在创建一个PrintWriter实例,但没有写入任何内容.

也许你打算包含outputFile.println(friendName)在for-loop里面?