使用java.io.package /如何从变量读取数据并将其存储在文件中?
问题描述:
有人可以请提供一个提示如何我可以从一个变量(一些字符串文件)中读取数据,该变量包含我的随机计算,并将输出存储在文本文件中,并可能与其一起工作。使用java.io.package /如何从变量读取数据并将其存储在文件中?
感谢, steliyan
答
我对你有2例;第一个是从文本文件读取,第二个是写入一个。
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());
}
}
}
谢谢!我做到了,但无法找到我的file.txt我搜索了程序目录,但没有这个名字的文件,没有任何文件。 – 2012-03-07 23:45:35
@StelyianStoyanov这可能是因为相对路径将文件放在意想不到的地方。尝试使用像“C:\\ test.txt”这样的绝对路径,以便找到/确认它。 – 2012-03-07 23:47:09
Riyad Kalla,感谢您的回复,但我使用的是unix机器,在这种情况下我该如何保存文件?谢谢! – 2012-03-07 23:56:56