流按流向分为两种:
输入流(读取数据)
输出流(写数据)
流按操作类型分为两种:
字节流 : 字节流可以操作任何数据,因为在计算机中任何数据都是以字节的形式存储的
字符流 : 字符流只能操作纯字符数据,比较方便。
File操作文件或文件夹
缓冲流:
我们知道,程序与磁盘的交互相对于内存运算是很慢的,容易成为程序的性能瓶颈。减少程序与磁盘的交互
,是提升程序效率一种有效手段。缓冲流,就应用这种思路:普通流每次读写一个字节,而缓冲流在内存中
设置一个缓存区,缓冲区先存储足够的待操作数据后,再与内存或磁盘进行交互。这样
,在总数据量不变的情况下,通过提高每次交互的数据量,减少了交互次数。
用字节缓冲流创建
public static void main(String[] args) {
try {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\a.jpg.jpg"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\a.jpg.jpg"));
byte [] b=new byte[1024];
int le=0;
while ((le=bis.read(b))!=-1) {
bos.write(b, 0, le);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
字节流的读取写入
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis=new FileInputStream("D:\\a.jpg.jpg");
fos=new FileOutputStream("D:\\b.jpg.jpg");
byte [] b=new byte[1024];
int le=0;
while ((le=fis.read(b))!=-1) {
fos.write(b, 0, le);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
字符流的读取写入
public static void main(String[] args) {
try {
BufferedReader br=new BufferedReader(new FileReader("d:\\abc.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("d:\\abd.txt"));
String le=null;
while ((le=br.readLine())!=null) {
bw.write(le);
bw.newLine();
}
bw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
字节流转换为字符流
public static void main(String[] args) {
BufferedReader br=null;
BufferedWriter bw=null;
br=new BufferedReader(new InputStreamReader(System.in));
try {
bw=new BufferedWriter(new FileWriter(new File("d:\\ccc.txt"), true));
String le="";
System.out.println("请输入内容");
while((le=br.readLine())!=null) {
if (le.equals("end")) {
break;
}
bw.write(le);
bw.newLine();
}
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
在控制台输入内容,输入end后会结束。并且会保存在D盘的ccc.txt中
在jvm内部,统一使用基于unicode字符集的字符编码,对于中文版操作系统来说,系统默认编码GBK
System.out.println(System.getProperty("file.encoding"));