簡體   English   中英

Java讀寫同一文件

[英]Java reading and writing to same file

我正在使用以下代碼在計算機中搜索特定文件,並將絕對路徑寫入文本文件。 我的問題是,每次我運行此代碼時,它都會向文本文件中添加重復的行,我只想添加當時未寫入文本文件中的行(文件路徑)(沒有重復)。。謝謝

public static void walkin(File dir) {
    String pattern = ".mp4";
    try {

        PrintWriter out = new PrintWriter(new BufferedWriter(
                new FileWriter("D:\\nawaaaaaa.txt", true)));
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkin(listFile[i]);
                } else if (listFile[i].getName().endsWith(pattern)
                        && listFile[i].isFile()) {
                    System.out.println(listFile[i].getPath());
                    out.write(listFile[i].toString());
                    out.write("\r\n");
                    // out.close();
                } else {
                    walkin(listFile[i]);
                }
            }
        }
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

如果您不想在文件中重復,則需要跟蹤已經寫入的文件名。 HashSet<String>為此。 但是令我驚訝的是,由於您始終在walkin()的頂部打開文件並且walkin()本身是遞歸的,因此上述代碼完全奏效。 您需要重新考慮一下代碼。 可能將PrintWriter作為參數傳遞到walkin()中。

由於您多次運行該代碼(“每次我運行此代碼,都會在文本文件中添加重復的行”),因此,一旦完成對該文件的寫入,便會讀取每一行並將其存儲在HashSet<String> 並使用另一個編寫器將其寫入文件。

BufferedWriter writer = new BufferedWriter(new FileWriter("filename"));
for (String eachUniqueLine: `Your hash set`) {
    writer.write(eachUniqueLine);
    writer.newLine();
}

(這很昂貴,因為您必須執行更多的I / O操作)

您的代碼對我有用,不知道您的問題是什么,如何調用它; 但是您可以對代碼進行一些優化,如下所示(只是非常快速的代碼,代碼會變得更好,但可以給您一個思路):

public class SomeTest {

    private static HashSet<String> filez = new  HashSet<String> (); 

    public static void walkin(File dir, PrintWriter out) {
        String pattern = ".mp4";
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].getName().endsWith(pattern) && listFile[i].isFile()) {
                    //System.out.println(listFile[i].getPath());
                    if (filez.add(listFile[i].getPath())) {
                        out.write(listFile[i].toString());
                        out.write("\r\n");
                    }
                } else {
                    walkin(listFile[i], out);
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            File dir = new File("C:\\mydir");
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new FileWriter("D:\\nawaaaaaa.txt", true)));
            walkin(dir, out);
            out.close();
        } catch (IOException e) {
           //
        }
    }
}

您可以使用filez哈希集打印內容,也可以在解析過程結束時寫入文件。

您需要將您的方法擴展為執行此類任務的類。

您有兩個主要問題:為每個目錄打開一個writer,然后調用walkin ,以解決不適用於您的邏輯的問題(然后再次打開writer)。

您應該嘗試設計一個能夠為您創建索引的類。

public static void main(String[] args) throws IOException {


    File createTempFile = File.createTempFile("mp4", ".idx");

    FileIndexer fi = new  FileIndexer(createTempFile.getAbsolutePath());

    fi.index("C:\\", "mp4");

    System.out.println(createTempFile);

}


public static class FileIndexer {

    private static final String END_OF_LINE = "\r\n";

    private final String outputPath;
    private final Set<String> index = new HashSet<String>();

    public FileIndexer(String outputPath) {
        this.outputPath = outputPath;
    }

    private boolean isValidPath(String path) {

        return outputPath != null && outputPath.trim().length() > 0; 

    }

    private boolean isValidIndexFile(File file) {

        return file.isFile() && file.canRead() && file.canWrite();

    }

    private void createIndexFile(File file) throws IOException {

        if(file.createNewFile() == false) {
            throw new IOException("Could not create index file");
        }

        this.index.clear();

    }

    private void readIndexFile(File file) throws IOException {

        isValidIndexFile(file);

        index.clear();

        BufferedReader bufferedReader = null;
        try {
             bufferedReader = new BufferedReader(new FileReader(file));

            String line;
            while((line = bufferedReader.readLine()) != null) {
                addToIndex(line);
            }
        } finally {
            if(bufferedReader != null) {
                bufferedReader.close();
            }
        }
    }

    private void addToIndex(String line) {
        index.add(line);
    }

    private PrintWriter openIndex() throws IOException {

        if(isValidPath(outputPath) == false) {
            throw new IOException(String.format("The outputPath is not valid: [%s]",outputPath));
        }

        File indexFile = new File(outputPath);

        if(indexFile.exists()) {
            readIndexFile(indexFile);
        } else {
            createIndexFile(indexFile);
        }

        return new PrintWriter(new BufferedWriter(new FileWriter(this.outputPath, true)));

    }

    public synchronized void index(String pathToIndex, String pattern) throws IOException {

        isValidPath(pathToIndex);

        PrintWriter out = openIndex();

        try {

            File elementToIndex = new File(pathToIndex);
            index(elementToIndex,pathToIndex, out);

        } finally {
            if(out != null) {
                out.close();
            }
        }
    }


    private void index(File elementToIndex, String pattern, PrintWriter out) {


        if(elementToIndex == null) {
            return;
        }


        if(elementToIndex.isDirectory()) {
            for(File file : elementToIndex.listFiles()) {
                index(file,pattern, out);
            }
        }

        if(elementToIndex.isFile() && elementToIndex.getAbsolutePath().endsWith(pattern)) {
            writeToIndex(elementToIndex, out);
        }
    }

    private void writeToIndex(File elementToIndex, PrintWriter out) {

        out.write(elementToIndex.getAbsolutePath());
        out.write(END_OF_LINE);

    }

}

解決了問題(順便說一句,我不確定這是否是最有效的解決方案).......

public static void main(String[] args) {

    try {
        File dir = new File("D:\\To Do");
        BufferedWriter out = new BufferedWriter(new FileWriter(
                "D:\\path.txt", true));

        walkin(dir, out);
        out.close();
        readfile();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } // Replace this with a suitable directory
        // walkin(new File("D:/to Do"));
}

public static void walkin(File dir, BufferedWriter out) throws IOException {
    String pattern = ".mp4";

    // BufferedWriter out = new BufferedWriter(
    // new FileWriter("D:\\path.txt",true));
    File listFile[] = dir.listFiles();
    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {
            if (listFile[i].getName().endsWith(pattern)
                    && listFile[i].isFile()) {
                if (filez.add(listFile[i].getPath())) {
                    // System.out.println(listFile[i].getPath());
                    out.write(listFile[i].toString());
                    out.write("\r\n");
                    // System.out.println(filez);

                }
            } else {
                walkin(listFile[i], out);
            }
        }
    }
}

public static void readfile() {

    BufferedReader br = null;
    String str;
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(
                "D:\\duplicate_free.txt"));
        br = new BufferedReader(new FileReader("D:\\path.txt"));
        while ((str = br.readLine()) != null) {
            if (files.contains(str)) {

            } else {
                files.add(str);
            }
        }
        for (String uniq : files) {
            out.write(uniq);
            System.out.println(uniq);
        }
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM