关于output到file和控制台的问题!谢谢!

jyf7356759 2008-02-19 09:08:05
FileOutputStream fOutStream;
PrintStream pStream;
try
{
fOutStream = new FileOutputStream(new File(outname));
pStream = new PrintStream(fOutStream);
System.setOut(pStream);
}catch(IOException e)
{
}
我现在用的这个方法,但是这样,output的所有东西都到那个outname的file里去了。
我想控制有的去outname,有的还是在控制台,可以和user继续互动,可以么? tyty!
...全文
139 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuxo84 2008-02-20
  • 打赏
  • 举报
回复
有办法了,那就在System.setOut(ps)之前,先记下目前的标准输出到哪里了.
PrintStream old = System.out;
这样如果想再设置回来就简单了:System.setOut(old);

import java.io.*;
public class Test
{
FileOutputStream fos;
PrintStream ps;
//for storing the old PrintStream
PrintStream old;

public void filePrint( String outName )
{
try
{
fos= new FileOutputStream( new File( outName ) );
ps = new PrintStream( fos );
//store the old PrintStream
old = System.out;
//set new PrintStream
System.setOut( ps );
}
catch( IOException ioe )
{

}
finally
{
try
{
ps.close();
fos.close();
}
catch( IOException ioe )
{

}
}
}

public void consolePrint( String message, PrintStream old )
{
System.setOut( old );
System.out.println( message );
}
}

jyf7356759 2008-02-20
  • 打赏
  • 举报
回复
晕,发现有问题,楼上给的好像还是不work.
我先用consolePrint,然后filePrint之后,就回不到consolePrint了。
fos= new FileOutputStream( new File(outName) );
ps = new PrintStream( fos );
System.setOut( ps );
这样是把output set成file.
能有办法把他set回console么?
jyf7356759 2008-02-19
  • 打赏
  • 举报
回复
能给个例子么?谢谢.
liang8305 2008-02-19
  • 打赏
  • 举报
回复
写两个方法分别调用
wuxo84 2008-02-19
  • 打赏
  • 举报
回复

import java.io.*;
public class Test8
{
FileOutputStream fos;
PrintStream ps;

public void filePrint( String outName )
{
try
{
fos= new FileOutputStream( new File( outName ) );
ps = new PrintStream( fos );
//System.setOut( ps );
}
catch( IOException ioe )
{

}
}

public void consolePrint( String message )
{
System.out.println( message );
}
}
wuxo84 2008-02-19
  • 打赏
  • 举报
回复
import java.io.*;
public class Test8
{
FileOutputStream fos;
PrintStream ps;

public void filePrint( String outName )
{
try
{
fos= new FileOutputStream( new File( outName ) );
ps = new PrintStream( fos );
//System.setOut( ps );
}
catch( IOException ioe )
{

}
}

public void consolePrint( String message )
{
System.out.println( message );
}
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧