Java Program to write a string into a file


In this program, You will learn how to write a string into a file in Java.


FileOutputStream fout = new FileOutputStream("abc.txt");

byte b[] = str.getBytes();

fout.write(b);


Example: How to write a string into a file in Java

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

class Test {

    public static void main(String args[]) {

        String str;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter String value :");
        str = sc.nextLine();

        try {
            FileOutputStream fout = new FileOutputStream("abc.txt");
            byte b[] = str.getBytes();
            fout.write(b);

        } catch (IOException e) {
            System.out.println(e);
        }

        System.out.println("\nSuccessfully Done");
    }
}

Output:

Enter String value :Hi John Smith
Successfully Done