一、File类:
定义:文件描述符,用于描述在磁盘上的一个文件,或目录
File 类构造器:
二、io读取xxx.properties文件
public class PropDemo{ public vo test(){ Properties prop = new Properties(); //1.绝对路径 File file = new File("/users/kechunwang/BaiCe/config.properties"); prop.load(new FileInputStream(file)); //读取key的value Object obj = prop.get("driver"); obj.sout; //2.相对于resources目录的相对路径 Properties prop1 = new Properties(); prop1.load(PropDemo.getClassLoader().getResourceAsStream("db/config.properties")); Object obj1 = prop.get("driver"); obj1.sout; } }
三、FileReader读取文件标准写法:
public class FileReaderDemo { public static void main(String[] args) { FileReader reader = null; try{ //文件描述 File file = new File("test.log"); //定义文件取流 reader = new FileReader(file); //文件读取 char[] buf = new char[256]; int len = 0; while ((len = reader.read(buf)) != -1){ System.out.println("len:"+len); //String构造,注意边界 String val = new String(buf,0,len); System.out.println(val); } // 理解的读取过程 // // while (len != -1) { // // len = reader.read(buf); // // if (len != -1) { // // String val = new String(buf, 0, len); // // System.out.println(val); // // } // } }catch (FileNotFoundException fnfe){ fnfe.printStackTrace(); }catch (IOException ioe){ ioe.printStackTrace(); }finally { //关流 if (null != reader){ try { reader.close(); }catch (IOException ioe){ ioe.printStackTrace(); } } } } }
四、OutputStream
public class OutputStreamDemo { public static void main(String[] args) throws IOException { FileOutputStream outputStream = null; try{ //定位文件描述 File file = new File("test.log"); //实例化要写文件的基本类FileOutputStream outputStream = new FileOutputStream(file); String str = "hello world111"; //写数据 outputStream.write(str.getBytes()); }catch (FileNotFoundException ffe){ System.out.println("文件没有"); }catch (IOException ioe){ System.out.println("写入失败"); }finally { //关流,千万要记得关闭 try { if (null != outputStream){ outputStream.close(); } }catch (IOException e){ e.printStackTrace(); } outputStream.close(); } } }
五、InputStream
public class IPDemo01 { public static void main(String[] args) { File file = new File("test.log"); // try (FileInputStream ins = new FileInputStream(file)){ byte[] buf = new byte[512]; int len = 0; while ((len=ins.read(buf))!= -1){ String val = new String(buf,0,len); System.out.println(val); } }catch (IOException ex){ throw new IllegalStateException(ex); } } public void test01(){ File file = new File("test.log"); try (InputStream ins = new FileInputStream(file)){ byte[] buf = new byte[512]; int len = 0; while ((len = ins.read(buf))!= -1){ String val = new String(buf,0,len); System.out.println(val); } }catch (IOException ioe){ throw new IllegalStateException(ioe); } } }