如何从文件读取文本(文本语言不固定)并执行一些操作将其写入另一个文件?

时间:2018-07-12 10:29:06

标签: java

我有一个用孟加拉语,英语,北印度语等语言编写的文本文件。我想阅读此文件。然后我要对该字符串执行一些操作。然后,最后,我将结果字符串写入另一个文件。

我尝试了此操作,但并不能解决我的问题。那么,我该怎么做才能解决我的问题?

BufferedReader read = new BufferedReader(
    new InputStreamReader(
        new FileInputStream  ("Input1.txt"), StandardCharsets.UTF_8) );
Writer writeFirst = new BufferedWriter(
    new OutputStreamWriter(
        new FileOutputStream("Input.txt",true), StandardCharsets.UTF_16));
String str =null ;
while ((str = read.readLine()) != null) {
     String[] words = str.split(" ");
     // will do some operation on those strings
     for(String u : words) {
         writeFirst.write(u + "     ") ;
      }
      writeFirst.write("\n") ;
}

输入:

i love my country
আমি আমার দেশকে ভালোবাসি 

我得到的输出:

��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I       l o v e       m y       c o u n t r y      
��I      l o v e      m y      c o u n t r y     
��i      l o v e      m y      c o u n t r y     
��i   l o v e   m y   c o u n t r y ��i   l o v e   m y   c o u n t r y ��i   l o v e   m y   c o u n t r y ��i   l o v e   m y   c o u n t r y   � �   �     � �   �   �     � �   �   �   �     � �   �   �   �   �   �   �     

1 个答案:

答案 0 :(得分:1)

您的代码基本上可以正常工作。如果必须使用UTF-16,我建议将输出文件的编码从 UTF-16 显式更改为 UTF-16BE

我对资源的使用有所改善:

public static void main(String args[]) {
    try (InputStream is = new FileInputStream(Paths.get(args[0]).toFile());
            Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader in = new BufferedReader(reader);
            OutputStream os = new FileOutputStream(Paths.get(args[1]).toFile(), true);
            Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_16BE);
            BufferedWriter out = new BufferedWriter(writer)) {
        String line;
        while ((line = in.readLine()) != null) {
            String[] words = line.split(" ");
            System.out.println(
                    String.format("writing line '%s' which has %d words",
                            line, words.length));
            // will do some operation on those strings
            for (String word : words) {
                out.write(word + "     ");
            }
            out.write("\n");
        }
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
}

生成的文件(在args[1]上给出)已正确编码。可以使用iconv将其转换为UTF-8来验证:

$ iconv -f UTF16BE -t UTF8 output.UTF16BE.txt
i     love     my     country     
আমি     আমার     দেশকে     ভালোবাসি 

如您所见,内容是正确的,并且在单词之间添加了空格。