更新時(shí)間:2022-07-27 11:42:50 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1618次
如何將Java文件輸出?動(dòng)力節(jié)點(diǎn)小編來為大家解答。
輸出指定文件夾里面的文件
package com.mtlk.Day_04;
import java.io.File;
public class PrFile {
public static void main(String [] args){
File file = new File("E:/網(wǎng)安"); //創(chuàng)建一個(gè)file對象接收E盤里面的文件
File[] fi = file.listFiles(); //將file里面的文件陳列出來放到fi里面
for(File f : fi){ //遍歷fi存在 f 里
System.out.println(f.getName());
}
}
}
輸出盤符文件內(nèi)容
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); //創(chuàng)建file 對象 存drives
if(!file.exists()){
continue; //文件不存在返回繼續(xù)遍歷
}
getFiles(file); //get file 文件
}
}
private static void getFiles(File file) { //處理getFile 異常
File[] childFiles = file.listFiles(); //將file里面的子文件放在child數(shù)組里面
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 里面繼續(xù)遍歷
}
}catch (Exception e){ //try catch 拋出文件異常 遇到?jīng)]有權(quán)限的文件直接拋出異常,拋給jvm處理
continue;
}
}
}
}
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743