[英]is it possible to remove a last line from a file via BufferedWriter in Java?
I have a servlet class. 我有一个servlet类。 Within the class, I use BufferedWriter#write(String) from Java 6 to create a text file on the fly.
在该类中,我使用Java 6中的BufferedWriter#write(String)即时创建文本文件。 When I inspected the file, there is a blank line created at the last line.
当我检查文件时,在最后一行创建了一个空白行。 Is there way I could remove it in a programmatic way via that class?
有什么办法可以通过该类以编程方式将其删除吗? Or should I use different API?
还是应该使用其他API?
================
data 1 recorded
================
--> a blank line needs in between
================
data 2 recorded
================
--> a blank line needs to be removed at last line
// trimmed down version of doPost method from a servlet class
protected void doPost(.....) {
......
BufferedReader reader = new BuffereReader(new ...)
BufferedWriter logger = new BufferedWriter(new...)
while ((line = reader.readLine()) != null) {
if (!line.equals("")) {
try {
doSomething(line,logger);
logger.write("=============\r\n"); // create a footer
logger.write("\r\n");
} catch (RuntimeException e) {
logger.write(" warning! " + e.getMessage() + "\r\n");
logger.write("=============\r\n"); // create a footer
logger.write("\r\n");
}
} // end of if stmt
} // end of while loop
....
} // end of doPost method
// trimmed down version
private void doSomething(String line, BufferedWriter logger) {
logger.write("=============\r\n"); // create a header
....
if (...) {
throw new RuntimeException("data is corrupted");
} else {
logger.write("data is good!\r\n");
}
}
No, you cannot remove it with that class. 不,您不能使用该类将其删除。 The API does not provide a way to do that.
API没有提供执行此操作的方法。 Instead, your code will have to know if it's dealing with the last line and when it is, skip passing that into the
BufferedWriter
. 相反,您的代码将必须知道它是否在处理最后一行,何时处理,请跳过将其传递到
BufferedWriter
。
You can iterate through the generated file and store each line into a list if it isn't empty 您可以遍历生成的文件并将每行存储为列表(如果不为空)
Then later you can write the new list to a file. 然后,您可以将新列表写入文件。
Chances are it's happening because of the way you're writing to the file though. 发生这种情况的可能是因为您写入文件的方式不同。 Share your code.
分享您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.