更新時間:2022-07-27 11:42:50 來源:動力節點 瀏覽1547次
如何將Java文件輸出?動力節點小編來為大家解答。
輸出指定文件夾里面的文件
package com.mtlk.Day_04;
import java.io.File;
public class PrFile {
public static void main(String [] args){
File file = new File("E:/網安"); //創建一個file對象接收E盤里面的文件
File[] fi = file.listFiles(); //將file里面的文件陳列出來放到fi里面
for(File f : fi){ //遍歷fi存在 f 里
System.out.println(f.getName());
}
}
}
輸出盤符文件內容
package com.mtlk.Day_04;
import java.io.File;
public class PrChild {
public static void main(String[] args){
String[] drives = {"c:/","d:/","e:/","g:/"}; //將 cdefg 存到drives中
for (String drive : drives){ //用 drive 遍歷drives
File file = new File(drive); //創建file 對象 存drives
if(!file.exists()){
continue; //文件不存在返回繼續遍歷
}
getFiles(file); //get file 文件
}
}
private static void getFiles(File file) { //處理getFile 異常
File[] childFiles = file.listFiles(); //將file里面的子文件放在child數組里面
int length = childFiles.length;
for(int i = 0;i<length;i++){ //遍歷文件的子文件
try{
File childFile = childFiles[i];
if (childFile.isFile()){ //是子文件則輸出
System.out.println(childFile); //childFile.delete(); 刪除子文件
}else {
getFiles(childFile); //不是則返回到getFiles 里面繼續遍歷
}
}catch (Exception e){ //try catch 拋出文件異常 遇到沒有權限的文件直接拋出異常,拋給jvm處理
continue;
}
}
}
}
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習