有人可以提供一个提示,告诉我如何从变量(某个字符串文件)中读取数据,该变量保存我的随机计算并将输出存储在文本文件中,并可能提供一些使用它的功能。
谢谢, 斯特利扬
最佳答案
我有两个例子给你;第一个是从文本文件中读取,第二个是写入文本文件。
import java.io.*;
class FileRead {
public static void main(String args[]) {
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
br.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.*;
class FileWrite {
public static void main(String args[]) {
String var = "var";
try {
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(var);
//Close the output stream
out.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
关于java - 使用java.io.package/如何从变量读取数据并将其存储在文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9610854/