使用bufferreader進行txt文檔的讀取並存儲時換行符丟失問題


應用場景:對上傳文件進行中傳保存時,發現使用

            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
            String readline = "";  
            sb = new StringBuffer();  
            while ((readline = br.readLine()) != null) {   
                sb.append(readline).append("\n");  
            }  

這種方式讀取文本文件保存后丟失部分換行符,后來參考了一下其他網友的方法改進后原樣保存了

參考了其他網友的部分內容如下(部分有改動,紅色為核心代碼):

最近遇到一個問題,從文件里面讀取文件內容,結果讀取出來的內容在進行下一步操作的時候,總是提示內容不正確。問題找到原因,所以記錄一下。

    對比讀出來的字符串,發現我所使用的讀取文件的方法,讀取出來的內容把文件中的換行給去掉了,所以導致驗證內容的操作失敗。一開始所使用讀取文件內容用的是BufferedReader,用到了BufferedReader的readLine,這個函數在讀取的時候“丟掉”了換行符,遇到換行符就返回,然后進行下一行的讀取,這樣,原來在文件里的的換行符就沒有返回到我們要打印出來的字符串里。所以最后改用FileInputStream的read,這樣就會一口氣把文件里面的內容都讀取出來,包括換行符。

    去掉換行符的讀取方法:

    public static String readFileWithoutN(File file,String filename)
    {
        StringBuffer sb = null;
        try {  

   InputStream in = new FileInputStream(file);

     byte[] head = new byte[3];

   in.read(head);

     if(head[0] == -1 && head[1] == -2)

      encode = "UTF-16";

     if(head[0] == -2 && head[1] == -1)

      encode = "Unicode";

     if(head[0] == -17 && head[1] == -69 && head[2] == -65)

      encode = "UTF-8";

     String encode = "gb2312";

   
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),encode));
            String readline = "";  
            sb = new StringBuffer();  
            while ((readline = br.readLine()) != null) {  
                System.out.println("readline:" + readline);  
                sb.append(readline);  
            }  
            br.close();  

// 寫入的方法
           Writer wrt = new BufferWriter(new InputStreamReader(...,encode));

   wrt.write(sb.toString());

     wrt.flush();

   wrt.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return sb.toString();
    }

   原樣讀取的方法:

       public static String readFile(File path,String filename) {
        String result = null;
        try {
            File file = new File(path, filename);
            if (!file.exists()) {
                return null;
            }
            FileInputStream inputStream = new FileInputStream(file);
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            result = new String(b);

 

// 寫入的方法

           Writer wrt = new BufferWriter(new InputStreamReader(...,encode));

   wrt.write(result);

     wrt.flush();

   wrt.close();


        } catch (Exception e) {
            e.printStackTrace(); 
        }
        return result;
    }


免責聲明!

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



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