文件复制和剪切File

private void archieve(File file) throws Exception {
		String receiveTime = (new SimpleDateFormat("yyyyMMddHHmmss"))
				.format(file.lastModified());
		String newFileName = file.getName().substring(0,
				file.getName().indexOf('.'))
				+ receiveTime + ".txt";
		//String newFile = getDir(file)+ newFileName;  
		//copy(file, new File(newFile));
		String newFile = archieveDir + newFileName;
		move(file, new File(newFile));
	}

	public static void copy(File oldfile, File newFile) throws Exception {
		try {
			int byteread = 0;
			int buffSize = (int) Math.pow(2, 10);
			if (oldfile.exists()) {
				InputStream is = new FileInputStream(oldfile);
				FileOutputStream fs = new FileOutputStream(newFile);
				byte[] buffer = new byte[buffSize];
				while ((byteread = is.read(buffer)) != -1) {
					fs.write(buffer, 0, byteread);
				}
				fs.close();
				is.close();
			}
		} catch (Exception e) {
			throw new Exception();
		}
	}

	public static void move(File oldfile, File newFile) throws Exception {
		if (!newFile.getParentFile().exists()) {
			newFile.getParentFile().mkdir();
		}
		boolean success = oldfile.renameTo(newFile);
		if (!success) {
			throw new Exception();
		}
	}

	private String getDir(File file) {
		String path = file.getPath();
		return path.substring(0, path.indexOf(file.getName()));
	}

 

你可能感兴趣的:(File)