[求助]这个程序,有2个问题

Steve_Samuelson 2008-04-21 09:31:38

package com.justdoit.io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class TestPrintStream1 {
public static void main(String[] args) {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream("d:\\log.dat");
ps = new PrintStream(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(ps!=null){
System.setOut(ps);
}
int length = 0;
for(char c =0;c<=1000;c++){
System.out.print(c+" ");
if(length++>100){
System.out.println();
length=0;
}
}
}
}

1.我D盘下没有log.dat文件,为什么不会报错?
2.什么时候使用PrintWrite?
...全文
89 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
joejoe1991 2008-04-21
  • 打赏
  • 举报
回复
DataOutputStream是字节流啊,
PrintWriter是字符流

这是最大的区别了
流太多,我也搞 不清,会那些最常用的就可以了。
Steve_Samuelson 2008-04-21
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 joejoe1991 的回复:]
PrintWriter这个我不知道怎么说,当你想把内存中的一个基本数据类型的值写入文件保存的时候,你就可以用它。
如果用PrintStream写的话,你看到的就会是乱码
[/Quote]
DataOutputStream不是用于将基本 Java 数据类型写到输出流当中吗?
刚学流,感觉有些乱......不知道怎么理清思路了......
joejoe1991 2008-04-21
  • 打赏
  • 举报
回复
输出流,在文件不存在的时候,自动创建,所以不会报异常
PrintWriter这个我不知道怎么说,当你想把内存中的一个基本数据类型的值写入文件保存的时候,你就可以用它。
如果用PrintStream写的话,你看到的就会是乱码
anqini 2008-04-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 caoyinghui1986 的回复:]
1.我D盘下没有log.dat文件,为什么不会报错?
因为你得到 ps 没有执行 ps.write() 一下 就会报错的。
2.什么时候使用PrintWrite?
带格式的字符输出流 可以用来输出字符串。
servlet 中 PrintWriter out = reponse.getWriter(); 就是用 的 printWriter;
[/Quote]
API里说的是,构造函数执行时候,没有找到文件就抛异常的...不知道为什么
Steve_Samuelson 2008-04-21
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 caoyinghui1986 的回复:]
1.我D盘下没有log.dat文件,为什么不会报错?
因为你得到 ps 没有执行 ps.write() 一下 就会报错的。
[/Quote]
PrintWrite的write()方法不会出异常的。不知道为什么!
Shine_Panda 2008-04-21
  • 打赏
  • 举报
回复
1.我D盘下没有log.dat文件,为什么不会报错?
因为你得到 ps 没有执行 ps.write() 一下 就会报错的。
2.什么时候使用PrintWrite?
带格式的字符输出流 可以用来输出字符串。
servlet 中 PrintWriter out = reponse.getWriter(); 就是用 的 printWriter;

62,623

社区成员

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

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