import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class TestFileInputOutputStream {
File file1 = new File("hello.txt");
public void testFileOutputStream(){
FileOutputStream fos = null;
try{
fos = new FileOutputStream(file1);
fos.write(new String("I love China,I love World!").getBytes());
}catch(Exception e){
e.printStackTrace();
}finally{
if(fos !=null){
try{
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
public void testFileInputStream(){
FileInputStream fis = null;
//Byte[] b = new Byte[20];
try{
fis = new FileInputStream(file1);
/*
* 读取方法一:
* int b = fis.read();
while(b!=-1){
System.out.print((char)b);
b = fis.read();
}*/
/*
* 读取方法二:
* int b;
while((b=fis.read()) != -1){
System.out.print((char)b);
}*/
/*
* 读取方法三:
* byte[] b = new byte[5];
int len;
while((len = fis.read(b)) !=-1){
for(int i=0 ; i<len ;i++){
System.out.print((char)b[i]);
}
}*/
//读取方法四:
byte[] b = new byte[5];
int len;
while((len = fis.read(b)) !=-1){
//通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
新 String 的长度是字符集的函数,因此可能不等于该子数组的长度。
String str = new String(b,0,len);
System.out.print(str);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(fis != null){
try{
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
public static void main(String[] args){
TestFileInputOutputStream tio = new TestFileInputOutputStream();
//tio.testFileOutputStream();
tio.testFileInputStream();
}
}