Java三章学习内容(File类,InputStream,OutputStream)

xiaoxiao2021-02-28  43

一.File构造文件对象 首先实例化 File类 并填写相应的路径,通过 .exists() 判断文件是否存在再进行文件创建 .createNewFile(); ,创建完毕后可以使用相应的方法进行查看( 变量名 .getxxxx) File file =new File("D:\\wuzhijie.txt");          //引用File类,构建文件镜像对象 file .exists();                                                  //判断文件或则目录是否存在,布尔类型 file .createNewFile();                                     //创建文件file .getName()                                            //查看文件名称 file. getAbsolutePath()                                 //查看绝对路径(全路径的意思) file .getPath()                                              //查看相对路径 file .length()                                                //查看文件大小(字节) 参考代码: public class Text4 { public static void main(String[] args) { File file =new File("D:\\wuzhijie.txt"); //引用File类,构建文件镜像对象 if( !file.exists()){ //判断文件或则目录是否存在,布尔类型 System.out.println("创建成功!!!"); try { file.createNewFile(); //创建文件代码 } catch (IOException e) { e.printStackTrace(); } }else{ System.out.println("已经存在文件"); System.out.println("文件名是:"+ file.getName()+"绝对路径是:"+ file.getAbsolutePath()+"相对路径是:"+ file.getPath()+"文件大小:"+ file.length()+"字节"); file.delete(); } }

}

二.InputStream(读取)首先实例化FileInputStream类,通过.read();方法读取元素,根据字符情况可能需要转换.read();                              //读取数据.close();                             //关闭流参考代码:public class Text5 { public static void main(String[] args) { try { FileInputStream fis =new FileInputStream("E:\\wuzhijie.txt"); //引用指定文件目录 int leng=0; //声明整形int变量用于存储数据 while ((leng=fis.read())!=-1) { //依次读取数据直到为空(-1)并放倒leng变量中 System.out.println((char)leng); //leng出来的是ascii码,需要使用Char变相应字符 } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}三.OutputStream(写入)先实例化FileOutputStream对象并引用目录,通过变量名.write()方法写入相应信息.write();                              //写入信息.close();                             //关闭流参考代码:public class Text6 { public static void main(String[] args) { OutputStream os = null; //实例化类 try { os =new FileOutputStream("D:\\wuzhijie.txt"); //引用指定文件目录 String str = "好好学习,天天向上"; //需要插入的字符 byte [] b = str.getBytes(); //因中文一字等于两字符,需使用byte储存 os.write(b, 0, b.length); //使用write方法(变量,位置,位置) } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { os.close(); //关闭流 } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}

转载请注明原文地址: https://www.6miu.com/read-2250069.html

最新回复(0)