要将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"的文件中。