要將Java生成的數據存入文件,可以使用Java的文件輸入輸出流(FileInputStream和FileOutputStream)或者使用Java的文件寫入器(FileWriter)來實現。
使用文件輸入輸出流的示例代碼如下:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
String data = "Hello, World!";
String filename = "output.txt";
try {
FileOutputStream outputStream = new FileOutputStream(filename);
outputStream.write(data.getBytes());
outputStream.close();
System.out.println("Data has been written to the file.");
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = new FileInputStream(filename);
int content;
while ((content = inputStream.read()) != -1) {
System.out.print((char) content);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用文件寫入器的示例代碼如下:
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
String data = "Hello, World!";
String filename = "output.txt";
try {
FileWriter writer = new FileWriter(filename);
writer.write(data);
writer.close();
System.out.println("Data has been written to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上兩個示例代碼都會將字符串"Hello, World!"寫入名為"output.txt"的文件中。