而不是重命名我的文件只是重复

时间:2017-06-05 16:26:20

标签: java file io inputstream outputstream

我有一个应该处理目录中文件的程序,如果文件大小超过50个字节,请将其删除。否则,如果文件大小小于50字节,程序应将args [1]文件重命名为allFilesContent.txt(同一目录),并将所有文件写入此文件,用" n" (110 ASCII码)。但是程序只是创建另一个文件并写入第一个args [1]文件。问题是什么?

public class Solution
{
    public static void main(String [] args) throws IOException
    {
        File path = new File(args[0]);
        File resultFileAbsolutePath = new File(args[1]);
        ArrayList<File> allFiles = new ArrayList<>();
        boolean isRenamed = false;

        for(File file : path.listFiles())
        {
            if(file.length() > 50)
            {
                FileUtils.deleteFile(file);
            }

            else if(file.length() <= 50)
            {
                if(!isRenamed)
                {
                FileUtils.renameFile(resultFileAbsolutePath, new File(resultFileAbsolutePath.getParent()+"\\allFilesContent.txt"));
                isRenamed = true;
                }
                if(!file.getName().equals(resultFileAbsolutePath.getName()))
                {
                allFiles.add(file);
                }
            }
        }

        Collections.sort(allFiles, new Comparator<File>()
        {
            @Override
            public int compare(File o1, File o2)
            {
                return o1.getName().compareTo(o2.getName());
            }
        });

        FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);

        for (File file : allFiles)
        {
            try(FileInputStream fileInputStream = new FileInputStream(file))
            {
                if(allFiles.indexOf(file) != 0) fileOutputStream.write(110);
                int data;
                while(fileInputStream.available() > 0)
                {
                    data = fileInputStream.read();
                    fileOutputStream.write(data);
                }
            }
        }

       fileOutputStream.close();
    }

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }
}

和FileUtils类

import java.io.File;

public class FileUtils
{

    public static void deleteFile(File file)
    {
        if (!file.delete())
        {
            System.out.println("Can not delete file with name " + file.getName());
        }
    }

    public static void renameFile(File source, File destination)
    {
        if (!source.renameTo(destination))
        {
            System.out.println("Can not rename file with name " + source.getName());
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

您有以下声明:“FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath,true);”

而不是“真实”放“假”。它应该工作。