-
package com.zrm.File_one; import java.io.File; import java.io.IOException; /** * 对File的操作 * 以及常用的方法如下演示 */ public class FileDemo { public static void main(String[] args) throws IOException { //创建一个文件对象 File file = new File("file.txt"); try { //当此文件名的文件不存在时创建此文件 file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } //测试此文件是否为可执行的正确文件 file.canExecute(); System.out.println(file.canExecute()); //测试此文件是否可读 file.canRead(); System.out.println(file.canRead()); //测试此文件是否可以修改 file.canWrite(); System.out.println(file.canWrite()); //在默认的临时目录里使用给定的前缀和后缀生成一个文件,File的static方法 try { File.createTempFile("zrm", "txt"); } catch (IOException e) { e.printStackTrace(); } // //删除此文件 // file.delete(); // //在虚拟机终止时删除文件 // file.deleteOnExit(); //测试此文件是否存在 file.exists(); //获取文件的路径 file.getAbsolutePath();//绝对路径 file.getCanonicalFile();//返回此抽象路径名的规范形式 file.getCanonicalPath();//返回此抽象路径名的规范路径名字符串 file.getPath(); //获取文件名字 file.getName(); } }
FileInputStream:
package com.zrm.File_one; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputStreamDemo { public static void main(String[] args) throws Exception { //创建要进行操作的文件 File file = new File("file.txt"); //创建流 FileInputStream fis = new FileInputStream(file); //读取操作 fis.read(); int length = 0; while ((length = fis.read()) != -1) { System.out.println((char) length); } //通过缓冲区来读取 byte buffer[] = new byte[1024];//缓冲大小 int read = 0; while ((read = (int) fis.read(buffer)) != -1) { System.out.println(new String(buffer, 0, read)); } //另外一种读取方式 int read0 = fis.read(buffer, 1022, 2);//偏移量off为缓冲数组buffer的起始偏移量 System.out.println(new String(buffer, 1022, read0));
//最后关闭流
fis.close();} }
FileOutputStream:
-
package com.zrm.File_one; import java.io.File; import java.io.FileOutputStream; public class FileOutputStreamDmeo { public static void main(String[] args) throws Exception { //进行操作的文件 File file = new File("fos.txt"); //创建此文件 file.createNewFile(); //创建流 FileOutputStream fos = new FileOutputStream(file); //写入int类型 fos.write(66); //写入byte[] fos.write("byte".getBytes()); //写入 //将 len字节从位于偏移量 off的指定字节数组写入此文件输出流 fos.write("zrm".getBytes(), 1, 2);//偏移量为写入的字节数组的偏移量,长度为要写入的长度 //同样的最后需要关闭流 fos.close(); } }