java文件一些操作

1、文件操作
public
static void main(String args[]) throws IOException { String dirPath = "d:/aaa/bbb/"; File fileDirPath = new File(dirPath); System.out.println(fileDirPath.exists()); //判断文件目录是否存在 if (!fileDirPath.exists()) { if (!fileDirPath.isDirectory()) { fileDirPath.mkdir(); } } String filePath = dirPath + "/4244.txt"; System.out.println(filePath); File file = new File(filePath); //判断文件是否存在 if (!file.exists()) { file.createNewFile(); } //写数据到文件 BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write("55555fsfddasf55"); out.write("aaaaaaaa"); out.close(); System.out.println("文件创建成功!"); // System.out.println(delAllFile(dirPath)); //删除文件 // file.delete(); //读取文件 FileInputStream fileInputStream = new FileInputStream(filePath); int i ; byte[] bytes = new byte[1024]; while ((i = fileInputStream.read(bytes))!= -1) { String s = new String(bytes); System.out.println(s); } fileInputStream.close(); }

 2、文件打包成tar

先导入pom:

<dependency>
            <groupId>org.xeustechnologies</groupId>
            <artifactId>jtar</artifactId>
            <version>1.1</version>
        </dependency>

 

/**
             * 文件打成tar
             */
            //原来的文件地址
            FileOutputStream dest;
            //打包后的tar地址
            TarOutputStream out;
            try {
                dest = new FileOutputStream(tarPath);
                out = new TarOutputStream(new BufferedOutputStream(dest));
                File f = new File(txtPath);
                out.putNextEntry(new TarEntry(f, f.getName()));
                BufferedInputStream origin = new BufferedInputStream(new FileInputStream(f));
                int count;
                byte data[] = new byte[2048];
                while ((count = origin.read(data)) != -1) {
                    out.write(data, 0, count);
                }
                out.flush();
                origin.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

 

posted @ 2021-08-30 15:03  阿罗luo  阅读(29)  评论(0编辑  收藏  举报