最近自己写代码,主要牵涉到了:文件夹的移动功能
这个是之前转载的:转载的 <-- 很全面、很强大
以下是本人总结的(若有不对之处,请多多指教,谢谢):
private static void moveToFloder(File pdfName) {
String oldPath = pdfName.getPath;
String newPath;
try {
int bytesum = 0;
int byteread = 0;
//新建一个文件的路径
File file =
new File(newPath + "\\" + pdfName.getName());
//判断该路径是否有这个文件
if (!file.isDirectory()) {
//可以创建多个文件夹,若出现文件访问失败,则要加上"getParentFile()","mkdir()"只能建立单个的文件夹
file.getParentFile().mkdirs();
}
//找到原文件,读取
InputStream inStream = new FileInputStream(oldPath);
//在新的路径下面写入文件,其中FILE对象的path和name用: "/" 隔开
FileOutputStream fs =
new FileOutputStream(newPath
+ "/"
+ pdfName.getName());
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
//找到旧路径的文件,删除
File delPdfName = new File(oldPath );
delPdfName.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
总结:
1、File file = new File(File pdf); --> 假若从外面传给pdf这个File对象,那么 pdf=path+"/"+name
2、
File file =
new File(newPath + "\\" + pdfName.getName()); // --> 这个是建立文件夹的时候用到的
3、path --> 要以”\\“结尾。
4、多文件加的新建用mkdirs(),
file.getParentFile().mkdirs() // -->之所以加上pdfName.getName(),是由于用了"gerParentFile()"方法,该路径才能新建出完整的路径
//例如: 预期:c:\test\MyLove --> 实际: c:\test\MyLove\1.txt 才会得到预期值。若不加上1.txt,则路径为:c:\test
5、对于mkdirs(),可以查看API去进行
谢谢