名前の変更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();			
		}

 

公開された217元の記事 ウォン称賛7 ビュー50000 +

おすすめ

転載: blog.csdn.net/Hodors/article/details/103057187
おすすめ