在Java中,可以使用FileWriter或者BufferedWriter类将字符串写入文件。下面是一个示例代码:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
String content = "Hello, World!";
try {
FileWriter fileWriter = new FileWriter("output.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(content);
bufferedWriter.close();
fileWriter.close();
System.out.println("String has been written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个例子中,首先创建一个名为output.txt
的文本文件,然后使用FileWriter和BufferedWriter将字符串"Hello, World!"写入文件中。最后关闭BufferedWriter和FileWriter。