Java 寫文件實現換行


第一種:

寫入的內容中利用\r\n進行換行

File file = new File("D:/text");
		
			try {
				if(!file.exists())
				file.createNewFile();
				
				FileOutputStream out=new FileOutputStream(file,false);
				StringBuffer sb=new StringBuffer();
				sb.append("10600257100120161201153103010 \r\n");
				sb.append("120161201KBS571009886631浙江目錄上傳120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000\n");
				out.write(sb.toString().getBytes("utf-8"));//注意需要轉換對應的字符集
				out.flush();
		                out.close();
				/*
                    FileOutputStream out = new FileOutputStream(file);  
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
                   writer.write(json);
writer.close();  
                                */
                   } catch (IOException e) { e.printStackTrace(); }

  第二種:

利用BufferedWriter的newline()方法

File file = new File("D:/text");
		
			try {
				if(!file.exists())
				file.createNewFile();
				
				FileWriter  out=new FileWriter (file);
				BufferedWriter bw= new BufferedWriter(out);  
				bw.write("10600257100120161201153103010 ");  
				bw.newLine();  
				bw.write("120161201KBS571009886631浙江目錄上傳120161201094425210009302359591120110422KBS00005595530ZZA571ZZA20161201094435fanzhipeng2000");  
				bw.newLine();   	
				bw.flush();
				bw.close();
								
			} catch (IOException e) {
				e.printStackTrace();
			}
		

  但是newLine在使用中可能會出現問題:

不同系統的換行符:

    windows -->   \r\n

    Linux         -->   \r

    mac         -->   \n

    我們一般開發是在 windows 下開發,而服務器一般情況下都是 linux。

    如果我們使用 newline 函數換行,在本機測試的時候,因為是 windows 環境,換行符是 \r\n ,打開文件時候自然文件是換行處理,沒有問題。

   當我們部署到服務器時候,服務器是 linux 環境,newline 讀取系統換行符是 \r ,導出到文件,文件的換行符是 \r,當我們把這個文件通過瀏覽器下載到 windows 時候,再打開文件將會出現沒有換行的問題。因為 windows 下對於 \r 的解釋並不是換行符。

   所以,我們在開發時候,如果需要指定文件在某些地方換行,則不能使用 newline 方法。必須手動指定換行符:\r\n 因為按照上面列舉的不同系統換行符看,如果字符串的末尾是  \r\n 在三個系統中,查看該文件,都會解釋為換行。

 

簡單整理!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM