Skip to content
Advertisement

Write CSV file inside zip file using FileSystem

I want read the CSV files inside the zip file and edit the record based on some condition. I am using FileSystem class to create zip file system and then edit csv files. I used the below code read csv files

public static List<String> getFileList() {
        List<String> fileList = new ArrayList<>();
        ZipFile zip = null;
        try {
            zip = new ZipFile(zipFile);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (entry.getName().contains("**") && !entry.getName().contains("***")) {
                    fileList.add(entry.getName());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileList;
    }

    public static void modifyTextFileInZip() throws IOException {
        Path zipfilePath = Paths.get(zipFile);

        try (FileSystem fs = FileSystems.newFileSystem(zipfilePath, null)) {
            for (String file : getFileList()) {
                Path source = fs.getPath(file);
                String tempFileDest = source.getParent().toString() + "/" + "temp_" + source.getFileName();
                tempFileDest = tempFileDest.replace(".red", "");
                Path temp = fs.getPath(tempFileDest);
                editFiles(source, temp);
            }
        }
    }

    public static void editFiles(Path source, Path dest) {
        CSVReader reader;
        try {
            reader = new CSVReader(new InputStreamReader(Files.newInputStream(source)));
            List<String[]> records = reader.readAll();
            Iterator<String[]> iterator = records.iterator();
            
            Optional<String> fileName =
            Files.list(source.getParent())
                    .filter(file -> file.getFileName().toString().endsWith("***") &&
                            !file.getFileName().toString().endsWith("****"))
                    .map(file -> file.toString())
                    .findFirst();
            //System.out.println(fileName);
            
            while (iterator.hasNext()) {
                String[] record = iterator.next();
                String val = null;
                if("****".equals(record[5])){
                    try {
                        val = fileName.orElseThrow(() -> new RuntimeException("File Not found"));
                        val = "**" + val;
                        //System.out.println(val);
                    } catch(Exception e){
                        System.out.println("File not Found");
                    }
                    record[5] = val;
                }
                
                for(String cell: record) {
                    System.out.print(cell);
                }
                System.out.println();          
            }
            
            Files.createFile(dest);
            PrintWriter outputFile = new PrintWriter(Files.newOutputStream(dest));
            CSVWriter writer = new CSVWriter(outputFile);
            writer.writeAll(records);

            writer.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

erro log =>

java.nio.file.FileSystemException: C:zipfileP003.zip: The process cannot access the file because it is being used by another process.

    at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:86)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
    at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
    at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
    at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
    at java.nio.file.Files.delete(Files.java:1126)
    at com.sun.nio.zipfs.ZipFileSystem.sync(ZipFileSystem.java:1294)
    at com.sun.nio.zipfs.ZipFileSystem.close(ZipFileSystem.java:277)
    at com.shrikant.Main.Main2.modifyTextFileInZip(Main2.java:60)
    at com.shrikant.EditCsvFilesApplication.main(EditCsvFilesApplication.java:21)

I wans able to read the and edit the files using inputStream from Path object and then pass it to CSVReader object. But when I pass outputStream to CSVWriter and try to write data to temp file and can’t see any changes inside zip file. And also I am getting a .tmp (zipfstmp3381860066025396844.tmp) file generated every I run my program.

I followed this => https://stackoverflow.com/a/43836969/20783127 to write this program

Don’t know what’s going wrong, I can anyone explain ?

I am trying read and edit the csv files in zip file using FileSystem class in java, but its not working

Advertisement

Answer

You did not zip.close(). Better use the try-with-resources syntax, which closes also when an exception is thrown or one returns inside the { }.

try (ZipFile zip = new ZipFile(zipFile)) {
    ...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement