To create a file with content in Java, you can use the write
method of the FileWriter
class.
For example, to create a file called "output.txt" with the content "Hello, World!" in the current directory, you can use the following code:
File file = new File("output.txt"); FileWriter writer = new FileWriter(file); writer.write("Hello, World!"); writer.close();
This creates a new file called "output.txt" in the current directory and writes the string "Hello, World!" to the file. If the file already exists, it is overwritten.
You can also use the append
method of the FileWriter
class to add content to the end of an existing file. For example, to append the string "Hello, World!" to the file "output.txt", you can use the following code:
File file = new File("output.txt"); FileWriter writer = new FileWriter(file, true); writer.append("Hello, World!"); writer.close();
To write a list of strings to a file, you can use a loop to write each string to the file. For example, to write the strings "line1", "line2", and "line3" to a file called "output.txt" in the current directory, you can use the following code:
File file = new File("output.txt"); FileWriter writer = new FileWriter(file); List<String> lines = Arrays.asList("line1", "line2", "line3"); for (String line : lines) { writer.write(line); writer.write(System.lineSeparator()); } writer.close();
This writes each string in the list to a separate line in the file.