在Java中,可以使用FileWriter或者BufferedWriter類將字符串寫入文件。下面是一個(gè)示例代碼:
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();
}
}
}
在這個(gè)例子中,首先創(chuàng)建一個(gè)名為output.txt
的文本文件,然后使用FileWriter和BufferedWriter將字符串"Hello, World!"寫入文件中。最后關(guān)閉BufferedWriter和FileWriter。