2015-07-19 60 views
0

如何讀取文件,然後將數據寫入java中的.txt文件?以下是我的代碼。我正在閱讀擴展名爲.ivt的文件。 .ivt中有一些表,重置是描述數據的全部內容的文本。我必須讀取存儲在文件中的文本,然後將其寫入文本文件。我能夠獲取數據並將其寫入文本文件中。但是,當我打開文本文件並查看所寫的內容時,會看到很多隨機符號和空格。然後,幾行文字從英文轉換爲法文。我正在努力尋找這種情況發生的原因。閱讀數據時是否發生此問題?或者代碼有問題嗎?Java:讀取文件,然後在文本文件上寫入數據

package description; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.util.ArrayList; 

public class FileDescription 
{ 
    public static void main(String[] args) 
    { 
     // create variables 
     ArrayList<String> fileLines = new ArrayList<>(); 
     String currLine; 

     // create file 
     File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt"); 

     FileInputStream fis = null; 
     BufferedReader br = null; 

     try 
     { 
      fis = new FileInputStream(file); 
      // construct buffered reader 
      br = new BufferedReader(new InputStreamReader(fis)); 
     } 
     catch (FileNotFoundException e) 
     { 
     } 

     try 
     { 
      while((currLine = br.readLine()) != null) 
      { 
       // add line to the arrayList 
       fileLines.add(currLine); 
      } 
     } 
     catch (IOException e) 
     { 
     } 
     finally 
     { 
      // close buffered reader 
      try 
      { 
       br.close(); 
      } 
      catch (IOException e) 
      { 
      } 
     } 

     // write ArrayList on file 
     PrintWriter pw = null; 

     try 
     { 
      pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"); 
     } 
     catch (IOException e) 
     { 
     } 

     for (int i = 0; i < fileLines.size(); i++) 
     { 
      pw.println(fileLines.get(i)); 
     } 
    } 
} 

回答

1

該代碼似乎是正確的。請記住關閉輸出文件。如果沒有指定其他的東西,你正在使用plaftorm編碼。我認爲這是一個編碼問題。您可以嘗試使用UTF-8編碼進行讀寫。

對於緩衝讀者

BufferedReader br = new BufferedReader(new InputStreamReader(
    new FileInputStream("filename.txt"), StandardCharsets.UTF_8)); 

而對於作家

pstream = new PrintWriter(new OutputStreamWriter(
        new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true); 

編輯結果,請使用UTF-8的編輯器。

Reference 1 Reference 2

+0

我覺得實在是太編碼問題。我在閱讀文件時得到了你提到的編碼方式,但是,請你解釋一下如何編寫編碼?我感到困惑的部分是 - csocket.getOutputStream()。另外,我將如何提供文件名寫入? – Deep

+0

我糾正了這個例子。我希望現在很清楚。 – xcesco

+0

現在感謝它的清晰 – Deep

相關問題