java重命名异常处理策略

File file = new File(newPath);
		if(!file.exists()) {
			File oldFile = new File(oldPath);
			FileInputStream in = new FileInputStream(oldFile);
			FileOutputStream out = new FileOutputStream(file);;

			byte[] buffer=new byte[2097152];
			int readByte = 0;
			while((readByte = in.read(buffer)) != -1){
				out.write(buffer, 0, readByte);
			}
			in.close();
			out.close();
		}else {
			//如果已经存在了,更改一个新的名字,再放到那里

			String Name = file.getName().replaceAll("[.][^.]+$", "");//不包含后缀
			String Suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);

			//新的策略,时间(MS时间)+随机数
			DateFormat format = new SimpleDateFormat("SSS");
			String formatDate = format.format(new Date());
			int random = new Random().nextInt(10000);
			String r = new StringBuffer().append(formatDate)
					.append(random).toString();
			//			System.out.println("生成了随机数" + r);			
			String finalNewPath = file.getParent() + File.separator + Name + r +"." + Suffix;
			//			System.out.println("New name is " + finalNewPath);
			File newfile = new File(finalNewPath);
			File oldFile = new File(oldPath);
			FileInputStream in = new FileInputStream(oldFile);
			FileOutputStream out = new FileOutputStream(newfile);;
			byte[] buffer=new byte[2097152];
			int readByte = 0;
			while((readByte = in.read(buffer)) != -1){
				out.write(buffer, 0, readByte);
			}
			in.close();
			out.close();			
		}

 

posted @ 2019-11-13 20:55  bH1pJ  阅读(20)  评论(0编辑  收藏  举报