FileWriteDemo 4-22

Post date: Mar 5, 2014 5:02:05 PM

package filewritedemo;

import java.util.Scanner; // Needed for Scanner class

import java.io.*; // Needed for File and IOException

public class FileWriteDemo {

/**

* @param args the command line arguments

*/

public static void main(String[] args)throws IOException {

// TODO code application logic here

String filename; // Filename

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 newline character,

keyboard.nextLine();

// Get the filename.

System.out.print("Enter the filename: " );

filename = keyboard.nextLine();

// Make sure the file does not exist.

File file =new File(filename);

if (file.exists())

{

System.out.println("The file=+"+filename

+ " already exists." );

System.exit(0);

}

//Open the file.

PrintWriter outputFile=new PrintWriter(file);

// Get data and write it to the file.

for (int i = 1; i <= numFriends; i++)

{

// Get the name of a friend.

System.out.print("Enter the nane of friend " +

"number " + i + ": ");

friendName = keyboard.nextLine();

// Write the name to the file.

outputFile.println(friendName);

}

// Close the t i l e.

outputFile.close();

System.out.println("Data written to the file. " );

}

}