intro
输入输出流是数据处理的通道,java为之有相应的类和接口。
文件输入流
package stream;
import java.io.file;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream{
public static void main(String args[]) {
trt{
File f = new File("d:/file.txt");
FileInputStream fis = new FileInputStream(f);
}catch(IOException e) {
e.printStackTrace();
}
}
}
要先通过File获得文件句柄,然后再作为参数传入FileInputStream流中。如果要输出,就喂入到FileOutputStream。
字节流
字符流也一样的。
以字节流的形式读取文件内容
用于以字节的形式读取和写入数据。
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream{
public static void main(String[] args) {
try{
File f = new File("d:/input.txt");
FileInputStream fis = New FilInputStream(f);
byte[] all = new byte[(int) f.length];
fis.read(all);
for(byte b : all){
Sytem.out.printlb(b);
}
fis.close();
}catch(IOException e) {
e.printStack();
}
}
}
创建了一个Byte数组,用于存储file的字节数据。一个ASCii码对应一个字节。
关闭流的方式
无论是输入流还是输出流,如果使用完之后,不关闭数据流,会产生对资源的占用。
在try中关闭
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream{
public static void main(String args[]){
try{
File f = new File("d:/input.txt");
FileInnputStream fis = new FileInputStream(f);
byte[] all = new byte[(int) f.length];
fis.read(all);
for(byte b : all) {
System.out.println(b);
}
fis.close(); //close the stream.
}catch(IOException e) {
e.printStackTrace();
}
}
}
在finally中关闭
当然也可以在finally中关闭,注意要在close前检查有没有成功创建文件流,即fis是否为空。
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream{
public static void main(String args[]){
try{
File f = new File("d:/input.txt");
FileInputStream fis = new FileInputStream(f);
byte[] all = new byte[(int) .length()];
fis.read(all); //从文件读到文件
for(byte b : all) {
System.out.println(b);
]
} catch(IOException e) {
e.printStackTrace();
} Finally{
if(fis != null) {
try{
fis.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
汉字的编码方式
留
Reference
[1] https://how2j.cn/k/io/io-encoding/695.html#nowhere