Avatar ·

How to create a file and write data to it in Java? Detailed guide

Hello everyone! I just started learning Java and encountered a problem that seems elementary, but I can't figure it out. I need to create a new file and write some text to it (for example, the string "Hello, World!"). I've tried a bunch of examples from the internet, but I keep getting errors or the file simply isn't created.\n\nHere's what I tried to do:\n\n
import java.io.*;\n\npublic class Main {\n    public static void main(String[] args) {\n        File file = new File("test.txt");\n        // Further I don't know what to write\n    }\n}\n
\n\nI've read about the FileWriter, BufferedWriter, and FileOutputStream classes, but I don't understand the difference between them and which one is better to use. When I try to write something like `FileWriter writer = new FileWriter(file