簡體   English   中英

我需要有關讀取和寫入文件的幫助

[英]I need help on Reading and Writing files

我的任務是編寫一個程序,在文本文件上編寫一些網站,然后提取具有相同頂級域的網站並將其寫入單獨的文本文件。 這是我的代碼:

FileWriter myWriter, comWriter, eduWriter, orgWriter, netWriter;
    File newFile = new File("URL.txt");
    newFile.createNewFile();

    try {
        myWriter = new FileWriter("URL.txt");
        myWriter.write("""
                yahoo.com
                google.com
                usl.edu
                battle.net
                CSU.edu
                shopee.com
                xyz.org
                spup.edu
                slideshare.net
                php.net""");
        myWriter.close();
        System.out.println("Successfully wrote to the file!");
    } catch (IOException e) {
        System.out.println("Program didn't write");
    }

    try {
        Scanner scanner = new Scanner(newFile);

        while (scanner.hasNextLine()) {

            String line = scanner.nextLine();

            if (line.endsWith(".com")) {
                comWriter = new FileWriter("com.txt");
                comWriter.write(line);
                comWriter.close();
            }
            if (line.endsWith(".edu")) {
                eduWriter = new FileWriter("edu.txt");
                eduWriter.write(line);
                eduWriter.close();
            }
            if (line.endsWith(".net")) {
                netWriter = new FileWriter("net.txt");
                netWriter.write(line);
                netWriter.close();
            }
            if (line.endsWith(".org")) {
                orgWriter = new FileWriter("org.txt");
                orgWriter.write(line);
                orgWriter.close();
            }

        }
    }
    catch (Exception e) {
        System.out.println("Error occurred");
    }

我的程序創建新的 txt 文件。 但是,它只打印一行。 例如,在我的 com.txt 文件中,它只打印“shopee.com”

有什么我想念的嗎? 改進? 或者可能是錯誤? 我希望有一個人可以幫助我。 謝謝你。

打開文件進行寫入的方式總是會截斷 output 文件。 如果您僅使用文件名調用FileWriter構造函數,則該文件將被打開以進行寫入並被截斷。

為了將 append 寫入文件,您應該使用帶有 boolean 參數的構造函數,該參數指定您是否想要 append :

comWriter = new FileWriter("com.txt", true);

您還可以使用 NIO.2 中的Files.write方法而不是FileWriter

List<String> lines = new ArrayList<>();
lines.add("yahoo.com");
lines.add("google.com");

Files.write(Paths.get("URL.txt"), lines);

或者

Files.write(Paths.get("URL.txt"), lines, StandardOpenOption.APPEND);

如果你想 append 到現有文件。

或者,您可以創建一個這樣的行列表:

List<String> lines = List.of("yahoo.com", "google.com");

自動寫入所有行后,文件將關閉。

有很多方法可以完成這種事情。 這是一個使用 Java 的NIO的示例:

創建 URL 列表文件:

List<String> urlList = Arrays.asList(new String[] {"yahoo.com", "google.com", "usl.edu",
                       "battle.net", "CSU.edu", "shopee.com", "xyz.org", "spup.edu",
                       "slideshare.net", "php.net"});
    
try {
    java.nio.file.Files.write(java.nio.file.Paths.get("URL.txt"), 
                              urlList, java.nio.charset.StandardCharsets.UTF_8);
    System.out.println("Successfully created the URL.txt file!");
}
catch (IOException ex) {
    System.err.println("Error creating the URL.txt file!" + 
                       System.lineSeparator() + ex.getMessage());
}

讀取 URL 列表文件並創建頂級域(TLD) 文件:

/* 
  Creates Top-Level Domain (TLD) files that will store respective Domain Name Strings.

  Returns a comma (,) delimited string containing the Number of TLD files created and
  the number of Domain Name Strings added to the various TLD files created (in that
  order).

  Output to console can be commented out or removed from this method.

  If the supplied source path does not exist then an 'IllegalArgumentexception' is
  thrown.

  If the supplied destination path does not exist then there will be an attempt to
  create it. 
*/
public static String createTopLevelFiles(String sourcePath, String destinationPath) {
    // Does Source file exist? Throw exception if not.
    sourcePath = sourcePath.replace("\\\\",File.separator).replace("\\",File.separator);
    if (!java.nio.file.Files.exists(java.nio.file.Paths.get(sourcePath))) {
        // No...
        throw new IllegalArgumentException("createTopLevelFiles() Method Error!"
                + "Source file can not be found! (" + sourcePath + ")");
    }

    // Read Source file domains content into a List Interface Oject:
    // =============================================================
    List<String> urlList = null;
    try {
        java.nio.file.Path path = java.nio.file.Paths.get(sourcePath);
        urlList = java.nio.file.Files.readAllLines(path, java.nio.charset.StandardCharsets.UTF_8);
        if (urlList == null || urlList.isEmpty()) {
            System.err.println("createTopLevelFiles() Method Warning! No Domains "
                             + "available within URL List source file!");
            return null;  // Exit with null due to failure;
        }
    }
    catch (IOException ex) {
        System.err.println("createTopLevelFiles() Method Error!"
                         + System.lineSeparator() + ex.getMessage());
        return null;  // Exit with null due to failure;
    }
    
    // =============================================================

    // Check Destination Path - Create it if it doesn't already exist:
    // =============================================================
    destinationPath = destinationPath.replace("\\\\",File.separator).replace("\\",File.separator);
    java.nio.file.Path destPath = java.nio.file.Paths.get(destinationPath);
    if (!java.nio.file.Files.exists(destPath)) {
        try {
            // Creating the new directory because it doesn't exist in local system.
            Files.createDirectories(destPath);
            // System.out.println("Destination Directory Successfully Created!");
        }
        catch (IOException ex) {
            System.err.println("Problem Occured While Creating The Destination "
                             + "Directory!" + System.lineSeparator() + ex.getMessage());
            return null;  // Exit with null due to failure;
        }
    }
    // =============================================================
    
    // Create the Top-Level Domain files:
    // =============================================================
    int fileCount = 0; // Keep count of TLD file creations.
    int failCount = 0; // Keep count of Saved Domain Name failures.
    for (String domain : urlList) {
        String fileName = domain.substring(domain.lastIndexOf(".") + 1) + ".txt";
        String filePath = new StringBuilder(destinationPath)
                              .append(File.separator).append(fileName)
                              .toString().replace("\\\\",File.separator)
                              .replace("\\",File.separator);
        try {
            java.nio.file.Path fPath = java.nio.file.Paths.get(filePath);
            // If the file doesn't already exist then create it...
            if (!java.nio.file.Files.exists(fPath)) {
                java.nio.file.Files.createFile(fPath);
                System.out.println("Successfully created the \"" + 
                        filePath.substring(filePath.lastIndexOf(File.separator) + 1) 
                        + "\" TLD file!");
                fileCount++;
            }
            // Is the domain name already in file? if so ignore it.
            List<String> tmpList = null;
            tmpList = java.nio.file.Files.readAllLines(fPath, java.nio.charset.StandardCharsets.UTF_8);
            if (tmpList.contains(domain)) {
                tmpList.clear();
                failCount++;
                continue;
            }
            // Append the domain name String to file...
            java.nio.file.Files.write(fPath, (domain + System.lineSeparator()).getBytes(java.nio.charset.StandardCharsets.UTF_8), 
                                      java.nio.file.StandardOpenOption.APPEND);
            System.out.println("Successfully added the \"" + domain + "\" domain name to the '" 
                    + filePath.substring(filePath.lastIndexOf(File.separator) + 1) 
                    + "' TLD file!");
        }
        catch (IOException ex) {
            failCount++;
            System.err.println("WARNING - Error creating the " + 
                    filePath.substring(filePath.lastIndexOf(File.separator) + 1) + 
                    " file! | " + ex.getMessage());
        }
    }
    // =============================================================
    
    // Failure results (delete this code if you like).
    // =============================================================
    if (failCount > 0) {
        System.err.println(failCount + " out of " + urlList.size() + 
                           " domain names failed to be added!");
        System.err.println("This could be due to the fact that the domain");
        System.err.println("name is already stored or, one or more domain"); 
        System.err.println("names were found to be invalid.");
    }
    // =============================================================
    
    /* Return the total number of TLD files created and
       the total number of domain names added to these 
       various TLD files.      */
    return new StringBuilder(String.valueOf(fileCount)).append(", ")
            .append(String.valueOf((urlList.size() - failCount))).toString();
}

如果本地文件系統不存在,上述方法將自動在本地文件系統中創建目標路徑(目錄路徑),並根據附加到每個域名的 TLD 域名自動確定在該目標路徑中創建所需的文件名細繩。 創建文件后,域名字符串將附加到其各自的文件中。 如果域名已包含在 TLD 文件中,則忽略該名稱並將失敗計數加 1。

閱讀代碼中的所有注釋。

使用示例:

String result = createTopLevelFiles("URL.txt", "D:\\Top-Level_Domains");
System.out.println();
System.out.println("Result is:  " + result);

控制台 output 示例:

Successfully created the "com.txt" TLD file!
Successfully added the "yahoo.com" domain name to the 'com.txt' TLD file!
Successfully added the "google.com" domain name to the 'com.txt' TLD file!
Successfully created the "edu.txt" TLD file!
Successfully added the "usl.edu" domain name to the 'edu.txt' TLD file!
Successfully created the "net.txt" TLD file!
Successfully added the "battle.net" domain name to the 'net.txt' TLD file!
Successfully added the "CSU.edu" domain name to the 'edu.txt' TLD file!
Successfully added the "shopee.com" domain name to the 'com.txt' TLD file!
Successfully created the "org.txt" TLD file!
Successfully added the "xyz.org" domain name to the 'org.txt' TLD file!
Successfully added the "spup.edu" domain name to the 'edu.txt' TLD file!
Successfully added the "slideshare.net" domain name to the 'net.txt' TLD file!
Successfully added the "php.net" domain name to the 'net.txt' TLD file!

Result is: 4, 10

在目標路徑中創建的 4 個 TLD 文件和 10 個域名被添加到這些文件中。

暫無
暫無

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

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