【问题标题】:read special characters from a file and write in another file using java [duplicate]从文件中读取特殊字符并使用java写入另一个文件[重复]
【发布时间】:2012-12-02 08:47:42
【问题描述】:

可能重复:
Read special symbols from file

我正在尝试将一个文件复制到另一个文件。该文件使用编码标准 UTF8 并且文件也包含特殊字符。程序无法以相同格式复制另一个文件中的特殊字符,该文件被盒子形状干扰 特殊符号。

 try 
  {
   BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(new File("path of the file")),"UTF8") ;
  BufferedWriter bw= new BufferedWriter(new OutputStreamReader(new FileOutputStream(new File("path of the output file");
    while(br.readLine()!=null)
   {
     //code here to read and write from a file to another.


    }

   }
  catch(Exception ex  
 { 
 ex.printStackTrace();
  }

【问题讨论】:

  • Mmmm...您是否也尝试设置编码并为 OutputStreamWriter 设置编码?
  • 这里缺少很多右括号。要写一个读行,你必须知道它是什么,你正在失去br.readLine() 返回的东西。

标签: java file input io output


【解决方案1】:
BufferedWriter bw = new BufferedWriter(
        new OutputStreamWriter(
            new FileOutputStream(new File("path of the output file")),
            "UTF-8"));

或者在 java 7 中使用Files.copy

【讨论】:

  • 在 FileOutputStream 构造函数中给定 UTF8 但结果仍然相同
  • 我想在 OutputStreamWriter 中。尝试使用JEdit 左右,检查原始文件。
  • @JoopEggen 如何在 Files.copy 中设置编码?
  • @HalfBloodPrince 因为必须按原样复制文件,所以不需要使用 Files.copy 进行编码。仅当文件被读入java String 变量然后写入时才需要指明文件的编码,因为java 在内部将所有文本保持为Unicode。如果您有需要转换编码的用例:代替 Files.copy 使用上面的解决方案,或使用带有字符集的 Files.readAllLines/write
猜你喜欢
  • 1970-01-01
  • 2015-04-02
  • 2023-04-05
  • 2022-01-03
  • 2021-01-23
  • 2020-05-03
  • 2021-04-02
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多