我正在使用其他程序将bin文件转换为xml,然后我尝试读取该文件。 使用以下代码:
File file = new File(currentPath + "/ammunition.bin");
File file2 = fileTools.convert(file);
ArrayList<String> asd = fileTools.readFile(file2);
我得到FileNotFoundException,&#34;文件正由另一个进程使用&#34;。 是什么让这个奇怪的是file.canRead()返回true,即使我得到了异常。 以下是代码的其余部分:
public ArrayList<String> readFile(File file) {
ArrayList<String> result = new ArrayList<>();
Scanner reader;
try {
reader = new Scanner(file, "UTF-8");
} catch (FileNotFoundException ex) {
boolean b = file.canRead();
StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
JOptionPane.showMessageDialog(null, errors.toString());
alertError("readFile\n" + b + " " + ex.getMessage());
return null;
}
while (reader.hasNext()) {
result.add(reader.nextLine());
}
reader.close();
return result;
}
public File changeFileExtension(File f, String ext) {
String name = f.getAbsolutePath();
int i = name.lastIndexOf(".");
name = name.substring(0, i) + "." + ext;
f = new File(name);
return f;
}
public File convert(File file) {
File binConverter = new File(this.currentPath + "\\GibbedsTools\\Gibbed.Avalanche.BinConvert.exe");
if (!binConverter.exists()) {
alertError("convert\nGibbedsTools is missing, it should be in\n" + this.currentPath + "\\GibbedsTools\\Gibbed.Avalanche.BinConvert.exe");
return null;
}
if (!file.exists()) {
alertError("convert\nFile does not exist\n" + file.getAbsolutePath());
}
String name = file.getName();
String extension = name.substring(name.lastIndexOf(".") + 1, name.length());
Runtime rt = Runtime.getRuntime();
try {
rt.exec("cmd.exe /c " + "\"\"" + this.currentPath + "\\GibbedsTools\\Gibbed.Avalanche.BinConvert.exe\" \"" + file.getAbsolutePath() + "\"\"");
} catch (IOException ex) {
alertError("binToXml\n" + ex.getMessage());
return null;
}
File file2 = changeFileExtension(file, extension.equals("xml") ? "bin" : "xml");
int timepassed = 0;
while (!file2.exists() || !file2.canWrite() || timepassed <= 50) {
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
alertError("binToXml\n" + ex.getMessage());
return null;
}
timepassed += 50;
if (timepassed > 3000) {
if (!file2.exists()) {
alertError("convert\nError, binconverter probably crashed (No xml file created after 3 seconds from passing file to binconverter)\n"
+ "xml file should be in:\n"
+ file2.getAbsolutePath() + " Found: " + file2.exists());
return null;
}
}
if (timepassed > 6000 && !file2.canWrite()) {
alertError("convert\nCan't write to the xml file after 6 seconds from passing the file to binconverter."
+ file2.getAbsolutePath() + " Can write: " + file2.canWrite());
return null;
}
}
return file2;
}
答案 0 :(得分:1)
而不是:
Runtime rt = Runtime.getRuntime();
.
.
.
试试这个:
Process p = Runtime.getRuntime().exec("cmd.exe /c " + "\"\"" + this.currentPath + "\\GibbedsTools\\Gibbed.Avalanche.BinConvert.exe\" \"" + file.getAbsolutePath() + "\"\"");
然后您可以使用以下方式等待它完成:
p.waitFor();
外部程序完成后再释放文件。 更好的解决方案是使用Processbuilder
您还可以使用
销毁该过程p.destroy();
当然尽量避免使用它。除非程序很难处理。