使用命令行参数时无法写入文件
Can't write to file while using command line arguments
当我不输入命令行参数时,我可以写入文件,但无论何时我输入命令行参数,它都不会写入。即使我什至没有使用命令行参数。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public Test () throws IOException {
String content = "writing...";
File file = new File("sample.txt");
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");
}
}
您需要 flush
从 RAM
到 HDD|SSD
的数据,所以:
try (FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw)) {
// Write the data to the memory
bw.write(content);
// You need to flush the data
bw.flush();
// Close the BufferedWriter
bw.close();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Failed to write the data on the file", ex);
}
当我不输入命令行参数时,我可以写入文件,但无论何时我输入命令行参数,它都不会写入。即使我什至没有使用命令行参数。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public Test () throws IOException {
String content = "writing...";
File file = new File("sample.txt");
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");
}
}
您需要 flush
从 RAM
到 HDD|SSD
的数据,所以:
try (FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw)) {
// Write the data to the memory
bw.write(content);
// You need to flush the data
bw.flush();
// Close the BufferedWriter
bw.close();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "Failed to write the data on the file", ex);
}