Answers for "How do you read/write a text file in Java?"

3

writing to a text file java

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Posted by: Guest on April-07-2020
0

java write to text file

import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class WriteToFile2 {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}
Posted by: Guest on October-22-2021
0

java how to read a text file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Scratch{
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File("filename"));
        input.next();       //returns next String
        input.nextLine();   //returns next Line
        input.nextBoolean();//returns next Boolean
        input.nextInt();    //returns next Int
        input.nextDouble(); //returns next double
        ...
    }
}
Posted by: Guest on February-17-2020

Code answers related to "How do you read/write a text file in Java?"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language