手记

Java实现上传文件到本地服务器

public static void main(String[] args) throws IOException {
		//目标路径
		String filePath = "E:"+File.separator+"test"+File.separator;
		File file = new File(filePath);
		//如果文件目录不存在,就执行创建		
		if(!file.isDirectory()){
			file.mkdirs();
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHss");
		//目标文件名称
		String targetName =sdf.format(new Date()) + ".jpg";
		System.out.println(targetName);
		//创建目标文件
		File targetFile = new File(filePath + targetName);
		FileOutputStream fos = new FileOutputStream(targetFile);
		
		//读取本地文件
		File localFile = new File("E:"+File.separator+"1.jpg");
		//获取本地文件输入流
		InputStream stream = new FileInputStream(localFile);
		
		//写入目标文件
		byte[] buffer = new byte[1024*1024];
		int byteRead = 0;
		while((byteRead=stream.read(buffer))!=-1){
			fos.write(buffer, 0, byteRead);
			fos.flush();
		}
		fos.close();
		stream.close();
	}
2人推荐
随时随地看视频
慕课网APP