集册 Java实例教程 使用PrintWriter将数据写入文件

使用PrintWriter将数据写入文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

593
使用PrintWriter将数据写入文件

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;
/** 
 来自 N o w  J a v a  . c o m**/

import java.util.Scanner;


/**

 * This program writes data to a file. It makes sure the

 * specified file does not exist before opening it.

 */


public class FilePrintWriteDemo {

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

    String filename;

    String friendName;

    int numFriends;


    // Create a Scanner object for keyboard input

    Scanner keyboard = new Scanner(System.in);

    /**
     from
    * 时   代     Java  公  众  号 - nowjava.com 
    **/

    // 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();


    // Open the file

    FileWriter fw = new FileWriter(filename, true);

    PrintWriter outputFile = new PrintWriter(fw);


    // 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 name of friend " + "number " + i + 
展开阅读全文