Java IO

关于window和linux在文件存储的一些注意点

  • window文件名不区分大小写
  • linux文件名区分大小写
  • windows中文件有:只读、隐藏

io.File

  • File(String)
  • File(String,String)
  • boolean isExists
  • boolean isFile
  • boolean isDirectory
  • boolean isHidden

  • long .lastModfied()

    获取到最后修改事假

  • long .length()

    获取到文件的大小

    该方法只能拿到文件的大小,对于文件夹的大小(内部文件占有的所有空间)扫描文件夹内的所有文件,然后累积得到

  • String [] .lists()

  • File [] .fileList()

  • String .getPareat()

  • File .getParentFile()

  • String .getAbsolutePath() 可能不对

  • String .getCanonialPath()

    获得到规范的路径

    Windows中可支持{"d://folder//a.txt","d:\foder\a.test"}两种方式,后者被定义为规范路径格式 未测试,应当测试!

  • mkdir

    创建单级目录

    if(!_File.exit()){
      if(_File.mkdir()) System.out.println("文件夹创建成功");
    }
  • mkdirs

    创建多级目录

  • boolean .renameTo(File)

  • boolean .delete()

  • void .deleteOnExit()

    程序退出时才删除,注意此函数的返回值为void,虚拟机在退出时做的只能是尽力去删除,所以返回值为null(但我感觉吗,返回值设置为boolean会更好一些)

  • long getTotalSpace()

    getTotalSpace\getFreeSpace\getUseableSpace三者用于查询_File实例位于的盘符的容量信息

  • long getFreeSpace()

  • long getUsableSpace()

案例:查询某个文件夹的占地大小

    /**
     * 查询某个文件夹的占地大小
     * @param folderPath
     * @throws FileNotFoundException 
     */
    
    public static long getFolderSize(String folderPath) throws FileNotFoundException {
        File folder=new File(folderPath);
        if(!folder.isDirectory() || !folder.exists()) {
            throw new FileNotFoundException("参数不是一个合法的文件夹路径");
        }
        
        return getFolderSizeIn(folder);
    }
    /**
     * 该方法仅供getFolderSize调用
     * @param f
     * @return 一个合法目录的占地大小
     */
    private static long getFolderSizeIn(File f) {
        File [] list=f.listFiles();
        long totalSize=0;
        for(File f01:list) {
            if(f01.isDirectory()) {
                totalSize+=getFolderSizeIn(f01);
            }
            else {
                totalSize+=f01.length();
            }
        }
        return totalSize;
    }

FileNameFileter

@FunctionalInterface
public interface FilenameFilter{
    boolean accept(File dir, String name);
}

实现该类的即可定义一个文件过滤器类,通过_File.list得到file的当前目录下的所有文件,当这样调用_File.list(FileNameFilter)时会更加文件过滤器的过滤规则对文件进行过滤得到一组期望的文件的文件名

    public static void main(String[] args) {    
        File file=new File("");
        FilenameFilter filter=new FilenameFilter() {
            
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".java");
            }
        };
        String []name=file.list(filter);
        System.out.println(Arrays.toString(name));
    }

今天一整天状态很不错,不知道是不是上课时能摸键盘的原因,对Java的时间和日期操作已经有很概括的认知了,后边也不打算继续把这块细化了,等到工作需要的时候再细化吧,然后其实还想了解的是一些历史性的东西,比如计算机元年啥的,不过这玩意,随缘吧。

到这个时候人已经有些疲乏了,有些测试还没有做完,但是也不打算做下去了,现在九点半,看了会纪录片,很棒有木有,打算回去了,洗漱下,骑着自行车逛逛岂不美哉。

IO流

IO流,输入输出流,计算机中输入和输出都是以内存为基准的,向外输被定为为输出,向内输被称为输入。

Java IO流:

  • 字符流和字节流

  • 节点流和包装流

Closeable<interface>

public interface Closeable extends AutoCloseable {
    public void close() throws IOException;
}

AutoCloseable

当一个类实现该接口时可以使用带资源的try语句,如:

try(FileInputStream fis=new FileInputStream(file)){
    //...
} catch (IOException e) {
    e.printStackTrace();
}

带资源的try语句是jdk7提供的。

InputStream

fileInoutStream

    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\t.txt");
        if(!file.exists() || !file.isFile()) {
            throw new FileNotFoundException("文件资源未找到");
        }
        try(FileInputStream f=new FileInputStream(file)){
            byte[] buf=new byte[1024];
            int len;
            while((len=f.read(buf,0,1024))!=-1) {
                System.out.println(new String(buf,0,len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\t.txt");
        if(!file.exists() || !file.isFile()) {
            throw new FileNotFoundException("文件资源未找到");
        }
        try(FileInputStream fis=new FileInputStream(file)){
            int b;
            while(true) {
                b=fis.read();
                if(b==-1) break;
                System.out.println((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\t.txt");
        if(!file.exists() || !file.isFile()) {
            throw new FileNotFoundException("文件资源未找到");
        }
        try(FileInputStream fis=new FileInputStream(file)){
            int length=fis.available();
            int b;
            for(int i=0;i<length;i++) {
                b=fis.read();
                System.out.println((char)b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

BufferInputStream

public static void main(String[] args) throws FileNotFoundException {
    File file=new File("W:\\t.txt");
    if(!file.exists() || !file.isFile()) {
        throw new FileNotFoundException("文件资源未找到");
    }
    try(FileInputStream fis=new FileInputStream(file);BufferedInputStream bfi=new BufferedInputStream(fis);){
        //带多个资源的try语句是可被接受的,多个资源使用分号分隔,最先定义或最先使用的资源最后被关闭
        System.out.println(fis.markSupported());
        System.out.println(bfi.markSupported());
        int i;
        boolean flg=true;  //标记?
        int count=0;  //标志第3位
        while(true) {
            i=bfi.read();
            if(i==-1 ) {
                if(!flg) {
                    bfi.reset();
                    flg=true;
                    continue;
                }
                break;
            }
            if(++count==3 && flg) {
                bfi.mark(count);
                flg=false;
            }
            System.out.print((char)i);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

FileOutputStream

    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\folder\\folder\\folder\\t.txt");
        if(!file.getParentFile().exists()) {
            if(!file.getParentFile().mkdirs()) throw new FileNotFoundException("文件不存在且无法创建父级目录");
        }
        
        try (FileOutputStream fos=new FileOutputStream(file)){
            fos.write((int)'a');
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

指定编码格式读写txt文件(实际上处理文本时更推荐室友Writer和Reader)

    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\folder\\folder\\folder\\t.txt");
        if(!file.getParentFile().exists()) {
            if(!file.getParentFile().mkdirs()) throw new FileNotFoundException("文件不存在且无法创建父级目录");
        }
        
        try (FileOutputStream fos=new FileOutputStream(file)){
            String str="今天天气很好,我想跟你亲亲";
            fos.write(str.getBytes(Charset.forName("GBK")));
            fos.write(str.getBytes(Charset.forName("UTF-8")));
            //fis.read(bytes...)
            //new String(bytes,Charset.forName("..."))
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

追加读写&文件换行

    public static void main(String[] args) throws FileNotFoundException {
        File file=new File("W:\\folder\\folder\\folder\\t.txt");
        if(!file.getParentFile().exists()) {
            if(!file.getParentFile().mkdirs()) throw new FileNotFoundException("文件不存在且无法创建父级目录");
        }
        
        try (FileOutputStream fos=new FileOutputStream(file,true)){
            for(int i=0;i<5;i++) {
                fos.write(new Date().toString().getBytes());
                fos.write("\r\n".getBytes());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

关于flush

写文件时是先将文件放到一个内存中的一个缓存区中,当缓冲区容量达到一定程度后,才会真正从内存写出去,flush作用时手动将该缓存区中的东西全部从内存写出去。另外当流关闭的时候,缓冲区中的数据也会全部写出去,大部分情况下不是很flush也没问题,但是显式的调用一次flush会是不错的选择。

文件复制 & 文件切割合并

标签

评论


© 2021 成都云创动力科技有限公司 蜀ICP备20006351号-1