开发者

Java program will not output to file

This is a very basic program for Uni which writes user data to a file. I have followed the instructions clearly yet it does not seem to output the data to a file. All it does is create an empty file. I'm using Ubuntu, if this makes a difference.

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.nex开发者_运维百科tLine();
        }

        // Close the file
        outputFile.close();
        System.out.println("Data written to the file.");
    }

}


You are creating a PrintWriter instance but nothing is being written to it.

Perhaps you meant to include outputFile.println(friendName) inside the for-loop?


Try

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜