1.FileInputStream
1.构造方法
new FileInputStream(String);
意思是创建一个对象,让这个对象指向某个文件,然后对这个文件进行读取操作,如果这个文件不存在
2.读取文件
读取文件使用read()方法;
如果每次读取一个字节,那么read方法返回的是这个字节的内容,也就是一个ascII码值,当没有其他字节的时候会返回-1
如果每次读取多个字节,需要首先定义一个byte数组a,然后让这个数组作为read的形参,此时read函数返回的是这个数组的长度,如果没有其他字节了,就会返回-1
示例:
//每次读取一个字节public static void readOne(String name){//FileInputStream,打印ascII码//假设文件当中的内容是abcdefg,这些字符每个字符一个字节,如果是汉字,每个字三个字节FileInputStream a = null;try{a = new FileInputStream(name);int result;while((result = a.read())!=-1){System.out.println(result);}//所以每次会打印一个字节的ascII码}catch(FileNotFoundException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();;}finally{try{if(a!=null) {a.close();}}catch(IOException e){e.printStackTrace();}}}//每次读取多个字节public static void readMore(String name){//FileInputStream//假设文件当中的内容是abcdefg,这些字符每个字符一个字节,如果是汉字,每个字三个字节FileInputStream a = null;try{a = new FileInputStream(name);byte num[] = new byte[3];//假设每次读取三个字节int result;while((result = a.read(num))!=-1){//他会把这个获取到的字节数赋值给result//可以把数组直接转成字符串来打印String temp = new String(num,0,result);//意思是在num当中从第0个字节开始读取result个字节,然后形成字符串让String指向它System.out.println(temp+"\t"+result+"个字节");
// for(byte o :num)
// System.out.println(o);}//每次提取三个字节}catch(FileNotFoundException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();;}finally{try{if(a!=null) {a.close();}}catch(IOException e){e.printStackTrace();}}}
2.FileOutputStream
1.构造方法:
1.new FileOutputStream(String);
2.newFileOutputStream(String,boolean);
3.共同点
以上两种构造方法都会创建一个对象让这个对象指向某个文件,如果这个文件不存在就会直接创建这个文件,如果这个文件存在就会进行写入,如果文件无法打开就会抛
4.区别
写入的时候:
第一种构造方法会清空原文件然后重新开始写入
第二种构造方法如果传入的布尔值为true说明存在这个文件,就会接续着原文件的内容进行写入
2.写入文件
1.使用write方法
2.write方法的使用
write(byte数组)
3.如何从String转byte数组:
使用getBytes方法
eg:
String a="asda";
byte b[] = a.getBytes();
//写入文件public static void write(String name,String name1){FileOutputStream a = null;FileOutputStream b = null;//写了两个文件,一个本来没有,一个本来就有try{a= new FileOutputStream(name);b=new FileOutputStream(name1,true);String str = "adwawdawdawdawd";String str1 = "java从入门到放弃";byte[] str2 = str.getBytes();byte[] str3 = str1.getBytes();a.write(str2);b.write(str3);a.flush();b.flush();}catch(FileNotFoundException e){e.printStackTrace();}catch(IOException e){e.printStackTrace();}finally{try{if(a!=null){a.close();}if(b!=null){b.close();}}catch(IOException e){e.printStackTrace();}}}
3. FileReader
与FileInputStream的用法一致,只不过在读取的时候读取多字节从byte[],变成了char[]
4.FileWriter
与FileOutputStream的用法一致,也是在写入文件的时候从write(byte数组)变成了write(String)
public static void wirterW(String name){FileWriter a = null;try {a = new FileWriter(name);String str ="这是FileWriter";a.write(str+"\n"+"已经另起一行了");a.flush();} catch (FileNotFoundException e){e.printStackTrace();}catch (IOException e) {e.printStackTrace();}finally{if(a!=null){try {a.close();} catch (IOException e) {e.printStackTrace();}}}}