Spring 프로젝트 가 시 작 될 때 데이터베이스 에서 파일 경 로 를 가 져 오고 로 컬 로 다운로드 합 니 다.

2583 단어 javaWeb
@Component
public class InitAction {

	@Autowired
	private FilePathService filePathService;

	/**
	 *      ,       ,                   
	 */
	@PostConstruct
	public void downFile() {

		Properties props = System.getProperties(); //        
		String osName = props.getProperty("os.name"); //       
		if (osName.matches(".*Mac.*")) {
			String basepath = "/tmp/";

			//          ,    
			List pathLists = new LinkedList();
			String filePath1 = basepath + "file";
			String filePath2 = basepath + "file2";

			pathLists.add(filePath1);
			pathLists.add(filePath2);

			for (String string : pathLists) {
				File file = new File(string);
				if (!file.exists()) {
					file.mkdirs();
				}
			}

			//        
			List lists = this.filePathService.findAllData();
			List downUrlLists = new LinkedList();
			String filePath = basepath + "file"; //     
			for (FilePath filePath : lists) {
				downUrlLists.add(filePath.getDown_url());
			}
			//           
			File file = new File(filePath);
			//          
			if (!file.exists()) {
				//         ,         
				file.mkdirs();
			}
			FileOutputStream fileOut = null;
			HttpURLConnection conn = null;
			InputStream inputStream = null;
			try {
				for (int i = 0; i < downUrlLists.size(); i++) {
					String downUrl = downUrlLists.get(i);
					String fileName = downUrl.substring(downUrl.lastIndexOf("/")); //         
					//     
					URL httpUrl = new URL(downUrl);
					conn = (HttpURLConnection) httpUrl.openConnection();
					//  Post      ,  get  
					conn.setRequestMethod("GET");
					conn.setDoInput(true);
					conn.setDoOutput(true);
					// post        
					conn.setUseCaches(false);
					//        
					conn.connect();
					//        
					inputStream = conn.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(inputStream);
					//               /  
					if (!filePath.endsWith("/")) {
						filePath += "/";
					}
					//      (               )
					fileOut = new FileOutputStream(filePath + fileName);
					BufferedOutputStream bos = new BufferedOutputStream(fileOut);

					byte[] buf = new byte[4096];
					int length = bis.read(buf);
					//     
					while (length != -1) {
						bos.write(buf, 0, length);
						length = bis.read(buf);
					}
					bos.close();
					bis.close();
					conn.disconnect();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}

좋은 웹페이지 즐겨찾기