How to write a string into a file in Java?

Member

by leta , in category: Java , 2 years ago

How to write a string into a file in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jarod , 2 years ago

@leta You can use java.io.FileWriter and class FileWriter to write string in file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.io.FileWriter;

class Main {
    public static void main(String[] args) throws Exception {
        FileWriter fw = new FileWriter("D:\\Java\\tst\\data.txt"); 
        
        fw.write("computertips.info"); 
        fw.close(); 
    }
}


Member

by dasia , a year ago

@leta 

To write a string into a file in Java, you can use the FileWriter or BufferedWriter class. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String content = "Hello, world!"; // string to write to file

        // create file object
        File file = new File("output.txt");

        try {
            // create FileWriter and BufferedWriter objects
            FileWriter fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);

            // write content to file
            bw.write(content);

            // close resources
            bw.close();
            fw.close();

            System.out.println("Successfully wrote to file.");
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}


In this example, we create a file object called "output.txt" and a string called "content" that we want to write to the file. Then, we create a FileWriter object and a BufferedWriter object and use the write method of BufferedWriter to write the content to the file. Finally, we close the BufferedWriter and FileWriter objects to release any system resources that they were holding.