java:基本输出流写入文件

2021-04-22  本文已影响0人  老林_

文件目录

image.png
public static void main(String[] args) throws IOException {
        String fileUrl =getFileUrl("G:/java_test/git/jBase/build/resources/main/file4WriteBit.txt") ;
                //getOrCreateFileUrl("file4WriteBit.txt");
        //文件存在的情况下使用二进制写入
        if(fileUrl!=null){
            try(FileOutputStream fileOutputStream=new FileOutputStream(fileUrl)) {
                fileOutputStream.write(87);
                fileOutputStream.write(80);
            }
        }
    }

获取/或创建文件

public static String getFileUrl(String fileUrl) throws IOException {
        File file=new File(fileUrl);
        if(!file.exists()){

            boolean newFile = file.createNewFile();
            if(newFile){
                return file.getPath();
            }
        }
        return null;
    }

获取文件路径

/**
     * build文件夹下创建文件
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String getOrCreateFile(String fileName) throws IOException {
        //获取文件
        URL resource = BaseWriteFile.class.getResource("/"+fileName);
        String fileUrl=null;
        //如果没有获取到文件则创建该文件
        if(resource==null){
            File file = new File("");
            //获取项目路径
            String canonicalPath = file.getCanonicalPath();
            String newFilePath = canonicalPath + "/build/resources/main/"+fileName;
            System.out.println(newFilePath);
            //G:\java_test\git\jBase/build/resources/main/file4WriteBit.txt
            file=new File(newFilePath);
            boolean createSuc = file.createNewFile();
            if(createSuc){
                fileUrl=newFilePath;
            }
        }else {
            fileUrl=resource.getPath();
        }
        return fileUrl;
    }
上一篇 下一篇

猜你喜欢

热点阅读