1. 程式人生 > >java 對檔案內容進行替換工作

java 對檔案內容進行替換工作

讀取檔案程式碼如下:

		File file = new File("C:/Users/Administrator/Desktop/test1.json");
		try {
			String content = FileUtils.readFileToString(file, "utf-8");
			System.out.println(content);
		} catch (Exception e) {
			e.printStackTrace();
		}

這是應該算是程式碼最少的去讀辦法了。

缺點:要匯入commons-io-2.4.jar 檔案

替換文字內的內容:

/**
	 * 替換文字檔案中的 非法字串
	 * @param path
	 * @throws IOException
	 */
	public void replacTextContent(String path) throws IOException{
			//原有的內容
			String srcStr = "name:";        
			//要替換的內容
	        String replaceStr = "userName:";     
	        // 讀  
	        File file = new File(path);   
	        FileReader in = new FileReader(file);  
	        BufferedReader bufIn = new BufferedReader(in);  
	        // 記憶體流, 作為臨時流  
	        CharArrayWriter  tempStream = new CharArrayWriter();  
	        // 替換  
	        String line = null;  
	        while ( (line = bufIn.readLine()) != null) {  
	            // 替換每行中, 符合條件的字串  
	            line = line.replaceAll(srcStr, replaceStr);  
	            // 將該行寫入記憶體  
	            tempStream.write(line);  
	            // 新增換行符  
	            tempStream.append(System.getProperty("line.separator"));  
	        }  
	        // 關閉 輸入流  
	        bufIn.close();  
	        // 將記憶體中的流 寫入 檔案  
	        FileWriter out = new FileWriter(file);  
	        tempStream.writeTo(out);  
	        out.close();  
	        System.out.println("====path:"+path);
		
	}