Description

Save text to text file

Demo

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

/**//from  w  w w .  j av  a2s .  c  om
 * This program writes data to a file. It makes sure the specified file does not
 * exist before opening it.
 */

public class Main {
  public static void main(String[] args) throws IOException {
    String filename;
    String friendName;
    int numFriends;

    numFriends = 4;

    // Get the filename.
    System.out.print("Enter the filename: ");
    filename = "a.txt";

    // 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 name of friend " + "number " + i + ": ");
      friendName = "aaa";

      // Write the name to the file.
      outputFile.println(friendName);
    }

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

  }
}

Related Topic