使用FileOutputStream写入.txt文件时遇到麻烦

时间:2015-05-12 03:10:41

标签: java file fileoutputstream

问题在于,当我读取一个字符串然后,尝试将每个字符分别写入.txt文件,尽管System.out.println将显示正确的字符,当我将它们写入一个字符串时.txt文件,对于's,它会写一些奇怪的字符。为了说明,这里有一个例子:假设我们有这一行Second subject’s layout of same 100 pages.,我们希望使用以下代码将其写入.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();       
}

对于单词subject'ssubject’s,书面文件看起来像这样。我不知道为什么会这样。

2 个答案:

答案 0 :(得分:0)

尝试以下内容。它让你不必处理字符编码。

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();
  }
}

答案 1 :(得分:0)

这样的事情怎么样:

// 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);

这一切都与上面评论的使用过的字符集有关。