我正在尝试使用以下函数写入Java文件:
public void writeTextFile(String filename, double s){
FileWriter output=null;
try{
output= new FileWriter(filename);
BufferedWriter writer=new BufferedWriter(output);
String ss = String.valueOf(s);
writer.write(ss);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
}
}
}
}
我也尝试过使用:
FileOutputStream out;
PrintStream prt;
try{
out= new FileOutputStream("result");
prt=new PrintStream(out);
prt.println(value);
prt.flush();
prt.close();
}
catch(Exception e){
System.out.println("File write error");}
但我最终得到了两个方法的空白输出文件。需要帮助!! :(
答案 0 :(得分:2)
这将有效,
public void writeTextFile(String filename, double s){
FileWriter output=null;
try{
output= new FileWriter(filename);
BufferedWriter writer=new BufferedWriter(output);
String ss = String.valueOf(s);
writer.append(ss);
writer.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
}
}
}
}
答案 1 :(得分:1)
嘿,它的简单错误就是你没有冲洗缓冲区,请在刷新和关闭流之前这样做。
将此添加到您的第一个代码
public static void writeTextFile(String filename, double s){
FileWriter output=null;
try{
output= new FileWriter(filename);
BufferedWriter writer=new BufferedWriter(output);
String ss = String.valueOf(s);
System.out.println("ss:"+ss);
writer.write(ss);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
答案 2 :(得分:0)
试试这个
使用此链接: Tutorial on file writing
链接中的代码:
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
答案 3 :(得分:-2)
如果你尝试怎么办?
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
基于本教程:http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
答案 4 :(得分:-2)
你必须刷新并关闭BufferedWriter而不是FileWriter。