package ss; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Locale; /** * IO流的操作 */ public class I3O { private static File f1; public static void main(String[] args) throws IOException { //io1();//创建目录,多级目录 //io2();//文件操作案例 //i3o();//文件的移动与命名 i4o();//文件批量改名 } private static void i4o() { String s = "user"; File f = new File(s); if (f.isDirectory()){ File[] fs = f.listFiles(); int index = 0; for (File s1:fs){ String filename= s1.getName().toLowerCase(); String ext = filename.substring(filename.lastIndexOf(".")); if(".png".equalsIgnoreCase(ext)){ String path = s1.getParentFile().getName(); String newfilename= String.format("ss_%03d%s",++index,ext); s1.renameTo(new File("d:/测试文件夹",newfilename)); } } } } private static void i3o() { f1 = new File("user/1.png"); /*System.out.println(f1.exists()); System.out.println(f1.isFile());*/ String path = f1.getParentFile().getName(); f1.renameTo(new File(path,"abc.jpg")); } private static void io2() throws IOException { //建立文件 File f1 = new File("aa"); if (f1.exists()||f1.isFile()){ f1.delete(); System.out.println("文件被删除了"); }else { f1.createNewFile();//建立空文件 System.out.println("文件被创建了"); } //写入文件,同时建立文件 使用try..with优点 会自动关闭流 try(var sop = new FileOutputStream("u.dat",true)){ sop.write("hello 中文".getBytes(StandardCharsets.UTF_8)); }catch (IOException e ){ throw new RuntimeException(); } //将当前系统的日期+jpg,字符串写入user.bat中并自动关闭占用系统的资源 try (var out = new PrintWriter("user.bat")){ out.printf("%tF.jpg",System.currentTimeMillis()); }catch (FileNotFoundException e ){ throw new RuntimeException(e); } //读取文件 try (var read = new FileReader("u.dat")){ while(read.ready()){ System.out.print((char)read.read()); } }catch (IOException e ){ throw new RuntimeException(e); } } private static void io1() { //创建目录 File f = new File("user"); if (!f.exists()){//判断目录是否存在 f.mkdir(); }else { System.out.println("目录已经存在"); } //创建多级目录 File f2 = new File("d:\\测试文件夹\\user\\a\\b"); if (!f2.exists()){ f2.mkdirs(); }else{ System.out.println("已经创建成功"); } } }