IO流
两类方法: read( ) write() close()
两个核心流: FileInputStream FileOutputStream
- File文件
-
文件流
-
FileInputStream / FileOutputStream (字节流) / FileReader / FileWriter(字符流)
-
缓冲流
-
BufferedInputStream / BufferedOutputStream /
-
BufferedReader / BufferedWriter
-
-
转换流
-
InputStreamReader / OutputStreamWriter
- 对象流----涉及序列化、反序列化
- ObjectInputStream / ObjectOutputStream
缓冲 字节 输入输出流 代码:
BufferedInputStream
BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream("D:\\IoTest\\a.txt")); int rs = -1; //每次获取的值打印,当没有值时返回-1,结束循环 while((rs = bis.read()) != -1){ System.out.print((char)rs); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(bis != null){ //关闭io bis.close(); } } catch (IOException e) { e.printStackTrace(); } }
BufferedOutputStream
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("D:\\IoTest\\aa.txt"));
String str="hello world";
//将字符串转换为字节数组
byte[] ByteStr = str.getBytes();
//字节数组写入文件中
bos.write(ByteStr);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(bos != null){
//关闭io
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
转换 输入输出流 代码:
InputStreamReader
FileInputStream fis = null; BufferedReader br = null; try { fis = new FileInputStream("D:\\IoTest\\a.txt"); // 使用InputStreamReader 把字节流转换为字符流 br =new BufferedReader(new InputStreamReader(fis)); //先一行一行的读 readLine() 属于BufferedReader的方法 //BufferedReader(Reader 字符流) String line=null; while((line = br.readLine()) != null){ System.out.println(line); }
OutputStreamWriter
FileOutputStream fos = null; BufferedWriter bw = null; try { fos=new FileOutputStream("D:\\IoTest\\ow.txt",true); bw = new BufferedWriter(new OutputStreamWriter(fos)); bw.write("啊呀呀呀"); bw.newLine(); bw.write("啊呀呀呀1"); bw.newLine(); bw.flush();
文件的递归
public static void main(String[] args) { new FileIterator().iteratorFile(new File("D:\\code42\\代码\\les28"),1);; } /** * srcFile: 查找的某个文件夹的File * level: 层 1层: 2个空格, 2层: 1+1 = 2 4个空格 * 3 6个 * @param srcFile * */ public void iteratorFile(File srcFile, int level){ //1.获取子文件,子文件夹 //subFiles 中包含 子文件, 子文件夹 // listFiles() --> 获取 les28文件夹的所有的子文件夹, 子文件 File[] subFiles = srcFile.listFiles(); //这个循环遍历的这个层所有的子元素 for (File file : subFiles) { for (int i = 0; i < level; i++) { System.out.print(" "); } if(file.isDirectory()){//如果是文件夹, 查找这个文件夹下的所有的子文件,子文件夹 //System.out.println(""); System.out.println(file.getName()); iteratorFile(file,level+1);// 方法递归, 执行调用的方法中的代码,而前一次的代码调用是暂停 }else{ //是文件 System.out.println(file.getName()); } } }