Javaexamples-file-delete
提供:Dev Guides
Javaの例-ファイルを削除する
問題の説明
ファイルを削除するには?
溶液
この例は、Fileクラスのdelete()メソッドを使用してファイルを削除する方法を示しています。
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter out = new BufferedWriter (new FileWriter("filename"));
out.write("aString1\n");
out.close();
boolean success = (new File("filename")).delete();
if (success) {
System.out.println("The file has been successfully deleted");
}
BufferedReader in = new BufferedReader(new FileReader("filename"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}catch (IOException e) {
System.out.println("exception occoured"+ e);
System.out.println("
File does not exist or you are trying to read a file that has been deleted");
}
}
}
結果
上記のコードサンプルは、次の結果を生成します。
The file has been successfully deleted
exception occouredjava.io.FileNotFoundException:
filename (The system cannot find the file specified)
File does not exist or you are trying to read a
file that has been deleted
以下は、Javaでファイルを削除する別のサンプル例です。
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\finddevguides7\\Desktop\\abc.txt");
if(file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
上記のコードサンプルは、次の結果を生成します。
abc.txt is deleted!