題目:在電腦D盤下創建一個文件爲HelloWorld.txt文件,判斷他是文件還是目錄,再創建一個目錄IOTest,之後將HelloWorld.txt移動到IOTest目錄下去;之後遍歷IOTest這個目錄下的文件。
解:
import java.io.IOException;
import java.io.File;
public class FileUtils {
public static void main(String[] args) throws IOException {
File file = new File ( "D:", "HelloWorld.txt" );
//boolean isCreate;
if (file.createNewFile () == true) {
System.out.println ( "創建目錄成功" );
} else
System.out.println ( "創建目錄失敗" );
if (file.isFile () == true) {
System.out.println ( "這是文件" );
} else
System.out.println ( "這是目錄" );
File file1 = new File ( "D:/IOtest" );
file1.mkdirs ();
try {
//調用File類的核心方法renameTo
if(file.renameTo(new File(file1.getAbsolutePath () + "/" + file.getName()))){
System.out.println("文件移動成功!目標路徑:{"+file1.getAbsolutePath()+"}");
} else {
System.out.println("文件移動失敗!起始路徑:{"+file.getAbsolutePath()+"}");
}
}catch(Exception e) {
System.out.println("文件移動出現異常!起始路徑:{"+file.getAbsolutePath()+"}");
}
String[] arr = file1.list ();
for (String string : arr) { //進行遍歷
System.out.println ( string );
}
}
}