1

首先,我正在写入一个文件,我需要再次读取该文件,但我发现正在写入的文件末尾有一个空行,这会导致问题。虽然我在写入文件时使用 replaceAll("\s","") 命令来避免字符串中的任何空格,但它会在末尾再次创建空格或空行,所以我该如何删除它以确保文件结束字符串在哪里结束,而不是在文件末尾有空格。这是夹头,有点长,但如果需要,我也会发布

str2= str2+","+str;
str2= str2.replaceAll("\\s","");
str2.replaceAll("(?m)^[ \t]*\r?\n", "");
File testFile1 = new File("G:/softwares/xampp/htdocs/Simulator/testFile1.csv");
File parent = testFile1.getParentFile();
if(!parent.exists() && !parent.mkdirs())
{
    throw new IllegalStateException("Couldn't create dir: " + parent);
}
FileWriter fw = new FileWriter(testFile1,false);        
PrintWriter pw = new PrintWriter(fw);
pw.println(str2);
pw.flush();
pw.close();
4

2 回答 2

1

Your str2.replaceAll() may be replacing a line at the end and leaving the line blank.

Use str2.trim() or move str2 = str2.replaceAll("\\s","") after the second replaceAll().

This will probably not fix the problem since PrintWriter adds a \n after every line. Try using an OutputStream.

Replace:

FileWriter fw = new FileWriter(testFile1,false);        
PrintWriter pw = new PrintWriter(fw);
pw.println(str2);
pw.flush();
pw.close();

with:

FileOutputStream out = new FileOutputStream(testFile1);
out.write(str2.trim().getBytes());
out.close();
于 2013-06-01T02:53:48.423 回答
0

You might trim() your String when writing (or when reading):

str2.trim();

For experience I must said that when you write in a file, generally a white space is added (It happened to me in an assembly program). So if you read any file again, you may trim() the content String, as another solution.

于 2013-06-01T02:53:18.487 回答