我尝试在文件中包含20个字符后删除文件。我已经查看了有关此问题的每个Stack Overflow问题,并且没有任何答案可行。我看过每一个地方,没有任何作用。 File.delete();
对我不起作用。它会写一个文件,每次按下一个按钮,它都会添加一个" 1"它。如果有20个1,则需要删除该文件。
示例代码:
String fileName1 = "data1.txt";
try {
FileWriter fw = new FileWriter(fileName1, true);
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.write("1");
bw.close();
} catch (IOException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Scanner scanner = new Scanner(new FileReader("data1.txt"));
String scannerData1 = scanner.nextLine();
if (scannerData1.equals("11111111111111111111")) {
//In here is where its supposed to delete the file.
}
} catch (FileNotFoundException ex) {
Logger.getLogger(StudentRandomizerJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:0)
似乎对我有用......
for (int index = 0; index < 50; index++) {
String fileName1 = "data1.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName1, true))) {
bw.write("1");
} catch (IOException ex) {
ex.printStackTrace();
}
boolean deleteMe = false;
try (Scanner scanner = new Scanner(new FileReader("data1.txt"))) {
String scannerData1 = scanner.nextLine();
if (scannerData1.length() >= 20) {
deleteMe = true;
}
} catch (IOException ex) {
ex.printStackTrace();
}
if (deleteMe) {
File file = new File(fileName1);
if (!file.delete()) {
System.out.println("!! Could not delete " + file);
} else {
System.out.println(file + " was deleted");
}
System.out.println(file + " exists = " + file.exists());
}
}
打印
data1.txt was deleted
data1.txt exists = false
data1.txt was deleted
data1.txt exists = false
也许您需要检查一下您是否拥有删除文件的正确权限(但如果您具有写入权限,则应该可以将其删除)并且您要删除您认为自己的文件&#39 ;重新删除