java將文件移動到另一個目錄


需求:將startPath文件夾下  文件名在在table.txt   中的文件移動到endPath文件夾下

table.txt中包含需要移動的文件名

startPath中有所有文件

endPath為目標文件夾

 

方法:File.renameTo()方法

public static void main(String[] args) throws SQLException {
try {
// 創建流對象
BufferedReader br = new BufferedReader(new FileReader("table.txt"));
List<String> list = new ArrayList<>();
String line = null;
while ((line = br.readLine()) != null){
list.add(line);
}

int success = 0;
int fail = 0;
String startPath;
String endPath;
startPath = "startPath";
endPath = "endPath";
File tmpFile = new File(endPath);//獲取文件夾路徑
if(!tmpFile.exists()){//判斷文件夾是否創建,沒有創建則創建新文件夾
tmpFile.mkdirs();
}

for (String str: list) {

File startFile = new File(startPath+"/"+str+".pdf");
//System.out.println(endPath + startFile.getName());
if (startFile.renameTo(new File(endPath+"/"+startFile.getName()))) {
System.out.println("文件移動成功!文件名:{"+str+"} 目標路徑:{"+endPath+"}");
success++;
} else {
System.out.println("文件移動失敗!文件名:{"+str+"}");
fail++;
}
}

System.out.println("success"+success);
System.out.println("fail"+fail);
}catch (Exception e){
e.printStackTrace();
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM