在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。