java工作常用簡單工具

鎮妖塔 發表於 2020-10-18

java工作常用簡單工具

檔案複製

當專案部署於伺服器上時,檔案的複製就沒有那麼方便了 
public class FileTransfer {
	public static void main(String[] args) throws IOException {
		String oldFilePath = "C:\\Users\\admin\\Desktop\\asd.txt";
		String newFilePath = "C:\\Users\\admin\\Desktop\\zzz.jpg";
		fileTransfer(oldFilePath, newFilePath);
	}
	public static void fileTransfer(String oldFilePath, String newFilePath) {
		try {
			File oldFile = new File(oldFilePath);
			if(!oldFile.exists()) {
        		return;
        	}
			File newFile = new File(newFilePath);
			File parentFile = newFile.getParentFile();
			if(!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if(!newFile.exists()) {
				newFile.createNewFile();
			}
			InputStream in = new FileInputStream(oldFile);
        	OutputStream out = new FileOutputStream(newFile);
        	byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.close();
            in.close();
            System.out.println(oldFilePath + "檔案複製成功");
		}catch (Exception e) {
			// TODO: handle exception
			System.out.println(oldFilePath + "檔案複製失敗");
			e.printStackTrace();
		}
	}
}

迴圈寫入檔案

有時需要將資料從資料庫中讀出,進行字串拼接生成sql,寫入指定檔案
public class CycleWrite {
	public static void writeContent(BufferedWriter bw) {
		//TO DO
	}
	public static void main(String[] args) {
		String txtFilePath = "c:\\user\\admin\\desktop\\xxx.txt";
		cycleWrite(txtFilePath);
	}
	public static void cycleWrite(String txtFilePath) {
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			File file =new File(txtFilePath);
			if(!file.exists()){
	        	file.createNewFile();
	        }
			fileWriter = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fileWriter);
			//----------------------------------------------------------------
			writeContent(bw);
			//----------------------------------------------------------------
			//bw.write(xxxx);
			bw.close();
			fileWriter.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("寫入完成");
	}
}

Txt檔案讀取

從txt檔案中讀取 拼接sql寫入指定檔案
public class ReadText {
	public static void main(String[] args) {
		String txtFilePath = "C:\\Users\\admin\\Desktop\\asd.txt";
		String targetFilePath = "C:\\Users\\admin\\Desktop\\xxx.txt";
		readTxt(txtFilePath, targetFilePath);
	}
	
	/**
	 * 	
	 * @param lineTxt 每一行的內容
	 * @param bw bw.write("xxx");
	 * @param index 索引
	 * @param tempMap 臨時引數
	 * @throws IOException
	 */
	public static void operationTxtContent(BufferedWriter bw, String lineTxt, int index, Map tempMap) throws IOException {
		//TO DO
	}
	
	/**
	 * 	讀取txt檔案
	 * @param txtFilePath txt檔案的路徑
	 * @param targetFilePath 結果檔案的路徑
	 */
	public static void readTxt(String txtFilePath, String targetFilePath) {
		InputStream inputStream = null;
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			String encoding="UTF-8";
			File file = new File(txtFilePath);
			if(file.isFile() && file.exists()) {
				File outFile =new File(targetFilePath);
				if(!outFile.exists()){
					outFile.createNewFile();
		        }
				inputStream = new FileInputStream(file);
				read = new InputStreamReader(inputStream,encoding);//考慮到編碼格式
				bufferedReader = new BufferedReader(read);
				
				fileWriter = new FileWriter(outFile.getAbsoluteFile());
				bw = new BufferedWriter(fileWriter);
				
				//每一行的字串
                String lineTxt = null;
                //========================================================
                //臨時引數封裝
                Map tempMap = new HashMap();
                Connection content = SqlConnect.getSqlLiteContent();
                tempMap.put("connection", content);
                //========================================================
                int i = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                	//=================================================================
            		try {
            			operationTxtContent(bw, lineTxt, i, tempMap);
            			i++;
            		} catch(Exception e) {
            			e.printStackTrace();
            		}
                    //=================================================================
            		//bw.write(sql);
                }
			}else {
				System.out.println("檔案不存在");
			}
			bw.close();
			fileWriter.close();
			bufferedReader.close();
			read.close();
			inputStream.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("讀取完成");
	}
}

xlsx表格讀取

工作中難免需要操作xlsx 讀出然後進行sql拼接 寫入檔案
需要POI的依賴
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>4.0.1</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>4.0.1</version>
</dependency>
public class ReadXlsx {
	public static void main(String[] args) {
		String xlsxFilePath = "C:\\Users\\admin\\Desktop\\xxx.xlsx";
		String targetFilePath = "C:\\Users\\admin\\Desktop\\test_appendfile_asd.txt";
		readXlsx(xlsxFilePath, targetFilePath);
	}
	/**
	 * 	操作內容
	 * @param bw 
	 * 	bw.write("xxx");
	 * @param row 當前行物件
	 * 	row.getCell(2).getStringCellValue();
	 * @param index 索引
	 */
	public static void operationXlsxContent(BufferedWriter bw, Row row, int index) {
		
	}
	public static void readXlsx(String xlsxFilePath, String targetFilePath) {
		BufferedWriter bw = null;
		FileWriter fileWriter = null;
		try {
			//用於解析 xls 檔案
			//HSSFWorkbook wordbook = new HSSFWorkbook(new FileInputStream(new File(xlsxFilePath)));
			//用於解析 xls檔案
			//HSSFSheet sheetAt = wordbook.getSheetAt(0);
			//用於解析 xlsx檔案
			XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(xlsxFilePath)));
			//頁籤
			//用於解析 xlsx檔案
			XSSFSheet sheetAt = workbook.getSheetAt(0);
			File file =new File(targetFilePath);
			if(!file.exists()){
	        	file.createNewFile();
	        }
			fileWriter = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fileWriter);
			
			//row.getCell(2).getStringCellValue();
			//======================================================
			int i = 0;
			for(Row row : sheetAt) {
				try {
					operationXlsxContent(bw, row, i);
					i++;
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
			//=======================================================
			//bw.write(sql);
			bw.close();
			fileWriter.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		System.out.println("讀取完成");
	}
}

xlsx寫入

當然這裡的寫入值得是迴圈寫入 複雜性的寫入 還是建議去直接手動去寫
public class WriteXlsx {
	public static void main(String[] args) {
		String filePath = "C:\\Users\\admin\\Desktop\\test_appendfile_asd.xls";
		String sheetName = "月報表";
		
		List titleList = new ArrayList<String>();
		titleList.add("姓名");
		titleList.add("性別");
		
		List keyList = new ArrayList<String>();
		keyList.add("name");
		keyList.add("sex");
		
		List content = new ArrayList<Map>();
		Map map1 = new HashMap();
		map1.put("name", "張三");
		map1.put("sex", "女");
		content.add(map1);
		
		Map map2 = new HashMap();
		map2.put("name", "李四");
		map2.put("sex", "男");
		content.add(map2);
		writeXlsxList(filePath, sheetName, titleList, keyList, content);
	}
	
	public static void writeXlsxList(String filePath, String sheetName, List<String> titleList, List<String> keyList, List<Map> content) {
		writeXlsxMain(filePath, sheetName, "list", titleList, keyList, content);
	}
	
	private static void writeXlsxMain(String filePath, String sheetName, String type, List<String> titleList,List<String> keyList, List<Map> content) {
		FileOutputStream fOut = null;
		try {
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet(sheetName);
			//------------------------------------------------------------
			//寫入列表
			xlsxContent(sheet, titleList, keyList, content);
			//-----------------------------------------------------------
			// 新建一輸出檔案流
			fOut = new FileOutputStream(filePath);
			// 把相應的Excel 工作簿存檔
			workbook.write(fOut);
			fOut.flush();
			// 操作結束,關閉檔案
			fOut.close();
		}catch(Exception e) {
			e.printStackTrace();
		}
		System.out.println("完畢");
	}
	/**
	 * 	寫入列表
	 * @param sheet
	 */
	private static void xlsxContent(HSSFSheet sheet, List<String> titleList, List<String> keyList, List<Map> content) {
		
		if(titleList.size() != keyList.size()) {
			System.out.println("標題的長度與內容長度不一致");
			return;
		}
		
		int rowCount = 0;
		//第一行
		HSSFRow row = sheet.createRow(rowCount);
		rowCount++;
		//就有幾列
		for(int i = 0;i < titleList.size();i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(titleList.get(i));
		}
		
		//就有幾行
		for(Map contentMap : content) {
			row = sheet.createRow(rowCount);
			int i = 0;
			for(String key : keyList) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(MapUtils.getString(contentMap, key));
				i++;
			}
			rowCount++;
		}
	}
}