Answer to Question #267098 in Java | JSP | JSF for Tarurendra Kushwah

Question #267098

Write a program to read and write data to a file.

1
Expert's answer
2021-11-16T13:52:32-0500
import java.io.*;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        //read file
        System.out.println("Enter the file path to read:");
        String filePathToRead = sc.nextLine();
        File file = new File(filePathToRead);

        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File doesn't exist");
        } catch (IOException e) {
            System.out.println("Failed to read file");
        }
        //read file

        //write to file
        System.out.println("Enter the file path to write:");
        String filePathToWrite = sc.nextLine();
        File writeFile = new File(filePathToWrite);
        String line = "Hello, test!";

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(writeFile))) {
            writer.write(line);
        } catch (IOException e) {
            System.out.println("Failed to write to a file");
        }
        //write to file
        
        sc.close();
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS