Java FileOutputStream 字符串写入
我一直遇到 Java 文件问题。它被设计为在测试文件中逐行写入日志。不幸的是,每次我调用它时它都会覆盖同一行。
如果有人能提供帮助,我将永远感激不已,因为这一直让我陷入困境!
代码如下。
public abstract class Log {
protected static String DefaultLogFileLocation = "c:\\LOG.txt";
public static void ToFile(String pInputString) {
FileOutputStream pOUTPUT;
PrintStream pPRINT;
try
{
pOUTPUT = new FileOutputStream(DefaultLogFileLocation);
pPRINT = new PrintStream(pOUTPUT);
pPRINT.println (pInputString + "\n");
pPRINT.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
I’ve been having issues with a Java File. It's designed to write line after line in a test file as a log. Unfortunately it overwrites the same line every time I call it.
If anyone can help I would be eternally grateful as this has been driving me up the wall!
Code Below.
public abstract class Log {
protected static String DefaultLogFileLocation = "c:\\LOG.txt";
public static void ToFile(String pInputString) {
FileOutputStream pOUTPUT;
PrintStream pPRINT;
try
{
pOUTPUT = new FileOutputStream(DefaultLogFileLocation);
pPRINT = new PrintStream(pOUTPUT);
pPRINT.println (pInputString + "\n");
pPRINT.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您忘记传递构造函数参数来指定需要将数据附加到文件。
另外,为什么不使用一些 Java 日志框架呢?例如 java.util.logging 或log4j
写入文件的 log4j 配置示例:
You forgot to pass constructor parameter to specify you need to append data to file.
Also, why you don't use some Java Logging Framework? E.g. java.util.logging or log4j
Example of log4j configuration to write to file:
我建议使用
FileOutputStream
构造函数 具有append
参数。一般来说,熟悉Javadocs,他们可以比这里的人更快地回答这样的简单问题。
I suggest using the
FileOutputStream
constructor that has anappend
parameter.Generally, get familiar with the Javadocs, they can answer simple questions like that much more quickly than people here.
尝试使用 pOUTPUT = new FileOutputStream(DefaultLogFileLocation, true);。请参阅 FileOutputStream()。
Try using
pOUTPUT = new FileOutputStream(DefaultLogFileLocation, true);
. See FileOutputStream().