Java 寫文件實現換行

第一種:java

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

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(); }

  第二種:json

利用BufferedWriter的newline()方法windows

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\napp

    Linux         -->   \r函數

    mac         -->   \n測試

    咱們通常開發是在 windows 下開發,而服務器通常狀況下都是 linux。.net

    若是咱們使用 newline 函數換行,在本機測試的時候,由於是 windows 環境,換行符是 \r\n ,打開文件時候天然文件是換行處理,沒有問題。

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

   因此,咱們在開發時候,若是須要指定文件在某些地方換行,則不能使用 newline 方法。必須手動指定換行符:\r\n 由於按照上面列舉的不一樣系統換行符看,若是字符串的末尾是  \r\n 在三個系統中,查看該文件,都會解釋爲換行。

 

簡單整理!!

相關文章
相關標籤/搜索