一、概念
Java中对文件的操作是以流的方式进行的。流是Java内存中的一组有序数据序列。Java将数据从源(文件、内存、键盘、网络)读入到内存中,形成了流,然后将这些流还可以写到另外的目的地(文件、内存、控制台、网络),之所以称为流,是因为这个数据序列在不同时刻所操作的是源的不同部分.
二、流的分类
Java中的流,按照数据流的方向不同可以分为:输入流和输出流。
按照处理数据单位不同可以分为:字节流和字符流.
按照功能的不同分,分节点流和处理流
代码:
public class
InputStreamTest
{
public static void main(String[] args) {
test();
}
public static void test() {
InputStream in = null;
//字节输入流InputStream 是抽象类,需要实例化他的子类FileInputStream《文件字节输入流》注意:使用路径要使用\\或者/
try {
in = new FileInputStream("D:\\test.txt");
int c =0;//定义一个变量来接收每次读取的数据
while((c=in.read())!=-1){//按字节读取文件,直到文件末尾返回-1
System.out.print((char)c);//输出对应的字节,将asic码值转化成对应的char
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class
OutputStreamTest {
public static void main(String[] args) {
OutputStream out = null;//字节输出流
try {
out = new FileOutputStream("D:\\OutputStream.java");
String s= "写个汉字试试";
out.write(s.getBytes());//通过getBytes方法将String字符串转化为byte数组
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class
ReaderTest {
public static void main(String[] args) {
Reader re=null;
try {
re = new FileReader("D:\\test.txt");//字符输入流
int c= 0;
while((c=re.read())!=-1){
System.out.print((char)c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(re!=null){
try {
re.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class
BufferdReaderTest {
public static void main(String[] args) {
BufferedReader buf = null;
try {
buf = new BufferedReader(new FileReader("D:\\test.txt"));
String s = null;
while((s=buf.readLine())!=null){
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(buf !=null){
try {
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class
BufferdWriterTest {
public static void main(String[] args) {
BufferedWriter bufwri= null;
try {
bufwri = new BufferedWriter(new FileWriter("e:\\text.txt"));
bufwri.write("1234");
bufwri.newLine();//
bufwri.write("122");
} catch (IOException e) {
e.printStackTrace();
}finally{
if(bufwri!=null){
try {
bufwri.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}