2015-07-19 227 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

相关问题