一、
1、创建FileInputStream 对象,构造方法中绑定要读取的数据
2、使用read 方法,读取问
3、释放资源
二、代码练习
1、
package Demo01;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Demo01InputStream {
public static void main(String[] agrs) throws IOException {
//1、创建FileInputStream 对象,构造方法中绑定要读取的数据
FileInputStream fis=new FileInputStream("C:\\rxp\\java\\21\\day21\\a.txt");
//2、使用read 方法,读取问
/*int len=fis.read();
System.out.println(len);
/*len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
len=fis.read();
System.out.println(len);
*/
int len=0;
while((len=fis.read())!=-1) {
System.out.println(len);
}
//释放资源
fis.close();
}
}
2、
package Demo01;
import java.io.FileInputStream;
import java.io.IOException;
public class Demo02IputStream {
public static void main(String[] agrs) throws IOException {
//1、创建FileInputStream 对象,构造方法中绑定要读取的数据
FileInputStream fis=new FileInputStream("C:\\rxp\\java\\21\\day21\\a.txt");
/*
byte[] bytes=new byte[2];
int len=fis.read(bytes);
System.out.println("读取到的长度"+len);
//System.out.println(bytes[0]);//取出数组里面的值
//System.out.println(bytes[1]);
//System.out.println(Arrays.toString(bytes));
System.out.println(new String(bytes));
len=fis.read(bytes);
System.out.println("读取到的长度"+len);
System.out.println(new String(bytes));
len=fis.read(bytes);
System.out.println("读取到的长度"+len);
System.out.println(new String(bytes));
len=fis.read(bytes);
System.out.println("读取到的长度"+len);
System.out.println(new String(bytes));
len=fis.read(bytes);
System.out.println("读取到的长度"+len);
System.out.println(new String(bytes));
*/
byte[] bytes=new byte[8];
int len=0;
while((len=fis.read(bytes))!=-1) {
System.out.println(len);
System.out.println(new String(bytes));
}
//3、释放资源
fis.close();
}
}
3、
package Demo02;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Demo02Reader {
public static void main(String[] agrs) throws IOException {
FileReader fr=new FileReader("C:\\rxp\\java\\21\\day21\\a.txt");
/*int len=0;
while ((len=fr.read())!=-1) {
System.out.println((char)len);
}*/
char[] cs=new char[9];
int len=0;
while ((len=fr.read(cs))!=-1) {
System.out.println(len);
System.out.println(new String(cs));
}
}
}
4、
package Demo02;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Demo02Wreiter {
public static void main(String[] agrs) throws IOException {
FileWriter fw=new FileWriter("C:\\rxp\\java\\21\\day21\\a.txt");
fw.write(100);
fw.flush();
fw.write(101);
fw.flush();
fw.write(102);
fw.flush();
fw.write(103);
fw.flush();
fw.close();
fw.write(103);
//fw.flush();
}
}