0
public void removeLine(String s) throws IOException, FileNotFoundException{ 

    File tempFile = new File("temp.txt"); 
    FileInputStream reader = new FileInputStream(sharkFile); 
    Scanner scanner = new Scanner(reader); 
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true)); 

    String currentLine; 
    while(scanner.hasNextLine()){ 
     currentLine = scanner.nextLine(); 
     String trimmedLine = currentLine.trim(); 
     System.out.println(trimmedLine); 
     trimmedLine.equals(sharkName); 
     if(trimmedLine.equals(sharkName)) continue; 
     writer.write(currentLine + System.getProperty("line.separator")); 
    } 

    scanner.close(); 
    scanner = null; 
    reader.close(); 
    writer.flush(); 
    writer.close(); 
    writer = null; 
    System.gc(); 
    if(!sharkFile.delete()){ 
     System.out.println("Could not delete file d"); 
     return; 
    } 
    if(!tempFile.renameTo(sharkFile)){ 
     System.out.println("Could not rename file"); 
     return; 
    } 
} 

私はstackoverflowで数多くのスレッドを実行し、それらの変更を実装しましたが、ファイルは削除されません。ヘルプをよろしくお願いいたします。なぜ私のファイルは削除されませんか?

+5

ユーザー権限を確認しましたか?あなたはどんなエラーを出していますか? – johan855

+0

IO例外があればどこかにキャッチしていますか? –

+0

'Files.delete()'を使う;少なくとも失敗時には意味のある例外が発生します。また、 'System.gc()'がなぜですか? – fge

答えて

0

コードの下の使用には、削除する前にファイルの名前を変更し、それはあなたが削除した後、ファイル名にアクセスしていることを表示されています:

try { //rename file first     
    tempFile.renameTo(sharkFile); 

    } catch (Exception e) { 
        JOptionPane.showMessageDialog(null, "Unable to rename.");       
        } 

try {      
    sharkFile.delete();        
    } 
catch(Exception e) { 
        JOptionPane.showMessageDialog(null, "Unable to delete.");      
        }      
+0

これはどのように役立ちますか?どのようにRandomAccessFileをBufferedReaderより良く使うのですか? –

1

File APIは、例えば、何かが失敗する理由を説明する上で悪名高い弱く、 File.delete()は単にbooleanを返し、値falseは理由を説明できません。

新しいPath APIを代わりに使用してください。

また、try-with-resourcesを使用してください(ご利用ください)。

Scannerが遅いので、BufferedReaderを使用するのが良く、改行で改行して書き込むには、PrintWriterを使用してください。

Path sharkPath = sharkFile.toPath(); 
Path tempPath = Paths.get("temp.txt"); 
Charset cs = Charset.defaultCharset(); 
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs); 
    PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) { 
    for (String currentLine; (currentLine = reader.readLine()) != null;) { 
     String trimmedLine = currentLine.trim(); 
     System.out.println(trimmedLine); 
     if (! trimmedLine.equals(sharkName)) 
      writer.println(currentLine); 
    } 
} 
Files.delete(sharkPath); // throws descriptive exception if cannot delete 
Files.move(tempPath, sharkPath); // throws exception if cannot move 
関連する問題