Avatar ·

How to create a file and write data to it in Java? (detailed guide)

Hi! I just started learning Java and already ran into a problem. I need to create a text file and write some data to it, for example, the string "Hello, World!". \n\nI tried using FileWriter, but I can't get it to work. Here is my code:\n\n```java\npublic class Main {\n public static void main(String[] args) {\n File file = new File("test.txt");\n file.createNewFile(); // compilation error here?\n FileWriter writer = new FileWriter(file);\n writer.write("Hello, World!");\n writer.close();\n }\n}\n```\n\nIntelliJ IDEA underlines the lines with `createNewFile()` and `FileWriter` in red. I don't understand what I'm doing wrong. They say I need to handle exceptions, but I don't know how. \n\nI've already read several articles in Russian, but everywhere the examples are