题目:在电脑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 );
}
}
}