简体   繁体   English

使用FileOutputStream将.txt文件写入.txt文件时出现问题

[英]Trouble writing 's into a .txt file, using FileOutputStream

The problem is that when I read a string and then, try to write each characters in separate line, into a .txt file, although System.out.println will show correct characters, when I write them into a .txt file, for the 's it will write some weird characters instead. 问题是,当我读取一个字符串,然后尝试将每行中的每个字符写入一个.txt文件中,尽管当我将它们写入一个.txt文件时, System.out.println将显示正确的字符。 's它会写一些奇怪的字符,而不是。 To illustrate, here is an example: suppose we have this line Second subject's layout of same 100 pages. 为了举例说明,这是一个示例:假设我们Second subject's layout of same 100 pages.Second subject's layout of same 100 pages. and we want to write it into a .txt file, using the following code: 并且我们想使用以下代码将其写入.txt文件:

public static void write(String Swrite) throws IOException {
   if(!file.exists()){
     file.createNewFile();
   }
   FileOutputStream fop=new FileOutputStream(file,true);

   if(Swrite!=null)
   for(final String s : Swrite.split(" ")){
     fop.write(s.toLowerCase().getBytes());
     fop.write(System.getProperty("line.separator").getBytes());
   }     
   fop.flush();
   fop.close();       
}

the written file would look like this for the word, subject's : subject’s . 书面文件的subject'ssubject’s I have no idea why this happens. 我不知道为什么会这样。

Try something like the following. 尝试类似以下的方法。 It frees you from having to deal with character encoding. 它使您不必处理字符编码。

PrintWriter pw = null;

try {
  pw = new PrintWriter(file);

  if (Swrite!=null)
    for (String s : Swrite.split(" ")) {
      pw.println(s);
    }
  }
}
finally {
  if (pw != null) {
    pw.close();
  }
}

How about something like this: 这样的事情怎么样:

// The file to read the input from and write the output to.
// Original content: Second subject’s layout of same 100 pages.
File file = new File("C:\\temp\\file.txt");
// The charset of the file, in our case UTF-8.
Charset utf8Charset = Charset.forName("UTF-8");

// Read all bytes from the file and create a string out of it (with the correct charset).
String inputString = new String(Files.readAllBytes(file.toPath()), utf8Charset);

// Create a list of all output lines
List<String> lines = new ArrayList<>();

// Add the original line and than an empty line for clarity sake.
lines.add(inputString);
lines.add("");

// Convert the input string to lowercase and iterate over it's char array.
// Than for each char create a string which is a new line.
for(char c : inputString.toLowerCase().toCharArray()){
    lines.add(new String(new char[]{c}));
}

// Write all lines in the correct char encoding to the file
Files.write(file.toPath(), lines, utf8Charset);

It all has to do with the used charsets as commented above. 如上所述,这都与使用的字符集有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM