How to save a string to a text file in Java: complete guide
Hello everyone! I just started learning Java and ran into a problem: I can't figure out how to properly save a string to a text file. I've read tons of articles, but they all suggest different approaches, and I'm confused.\n\nI need the program to read some data from the user (for example, text entered via Scanner), and then write it to a file. I tried several options, but either the code doesn't work, or the file is created empty.\n\nHere is one of my failed experiments:\n\n
import java.io.*;\n\npublic class Test {\n public static void main(String[] args) {\n String text = "Hello, world!";\n File file = new File("output.txt");\n \n try {\n file.createNewFile();\n FileWriter writer = new FileWriter(file);\n writer.w