JAVA之多級目錄創建與寫txt文件

public boolean save2Txt() {
		if(drcProInfo.getSave2Txt()) {
			String txtPath = drcProInfo.getSave2TxtPath() +  "/" + getCurrDateStr() + ".txt";
			String content = CommTool.getHexString(srcData);
			return saveContent2Txt(content,txtPath);
		}
		return true;
	}
	
	public boolean check2CreatePath(String fileDir) {
		 String paths[] = fileDir.split("\\\\");  
		   String dir = paths[0];  
		   for (int i = 0; i < paths.length - 1; i++) {//注意此處循環的長度  
		       try {  
		           dir = dir + "/" + paths[i + 1];  
		           File dirFile = new File(dir);  
		           if (!dirFile.exists()) {  
		               dirFile.mkdir();  
		           }  
		       } catch (Exception err) {  
		           return false; 
		       }  
		   }
		   return true;
	}
	
	public boolean saveContent2Txt(String content,String txtPath) {
		File file = new File(txtPath);
		try {
			
			String parentDir =file.getParent();
			if (!check2CreatePath(parentDir))      
			{        
				logger.error(drcProInfo.getParseDataName()+",創建路徑失敗:" + parentDir);
			    CommTool.printInfo(drcProInfo.getParseDataName()+",創建路徑失敗:" + parentDir);
				return false; 
			}
			
			if(!file.exists()) {
				file.createNewFile();
			}
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file,true),"GB2312");
			BufferedWriter bw = new BufferedWriter(osw); 
			bw.write(getCurrDatetimeStr() + " " + content+"\r\n");
			bw.close();
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(drcProInfo.getParseDataName()+",將數據保存到TXT失敗:" + e.getMessage());
		    CommTool.printInfo(drcProInfo.getParseDataName()+",將數據保存到TXT失敗:" + e.getMessage());
			return false;
		}
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章