InputStream&OutputStream&FileInputStream&O

[color=red]thinking in OutputStream:[/color]

包含了1个抽象的方法,所有的子类都必须继承,还有4个其他的方法,子类可以override来提供更加丰富的功能。

public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length) throws IOException
public void flush( ) throws IOException
public void close( ) throws IOException

System.out 是一个静态的 PrintStream ,它实现了write(int b),此方法接受整形的参数,无标志的type,范围是0-255,如果大于255,则取值255。

System.out.write(40); 在控制台会输入'(',这个并不是write方法的特性,而是控制台的特性。
区别于System.out.print();

当参数为byte数组时,数组的大小会影响程序的性能,本地输入1024,网络128。
例子:

String s = "How are streams treating you?";
byte[] data = s.getBytes( );
System.out.write(data);

为什么会输入原来的句子,也是console的特性。


[color=red]thinking in InputStream[/color]它的方法:
public abstract int read( ) throws IOException

它从输入流读一个byte,并返回所读,为什么返回值不是byte,而是int,因为返回-1表示到达输入流的尾端了,所以它将返回0-255的int。

当有一个byte要读的时候,它表示 -128-127,可以转换成int:
int b=b>0?b:256+b;


试试这代码:

import java.io.*;
public class StreamPrinter {
public static void main(String[] args) {
try {
while (true) {
int datum = System.in.read( );
if (datum == -1) break;
System.out.println(datum);
}
}
catch (IOException ex) {
System.err.println("Couldn't read from System.in!");
}
}
}


读chunk
public int read(byte[] data) throws IOException
public int read(byte[] data, int offset, int length) throws IOException

public int available( ) throws IOException

此方法判断还有多少字节可以读取。返回-1,表示无。

public long skip(long bytesToSkip) throws IOException

跳过多少个字节。

输入w,输出w
package com.elharo.io;
import java.io.*;
public class StreamCopier {
public static void main(String[] args) {
try {
copy(System.in, System.out);
}
catch (IOException ex) {
System.err.println(ex);
}
}
public static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}
}
}



[color=red]thinking in FileInputStream[/color]
FileInputStream 有三种构造函数:
public FileInputStream(String fileName) throws IOException
public FileInputStream(File file) throws FileNotFoundException
public FileInputStream(FileDescriptor fdObj)


try {
FileInputStream fis = new FileInputStream("README.TXT");
for (int n = fis.read(); n != -1; n = fis.read( )) {
System.out.write(n);
}
}
catch (IOException ex) {
System.err.println(ex);
}

能从文件中读取内容,并显示,注意是write(),而不是print()。
其中Readme.txt是在 System.getProperty("user.dir") 下
还有System.getProperty("user.home")也是常用的。
在Java中"d:\\1.txt"或者"d:/1.txt"

[color=red]thinking in FileOutputStream[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值