簡體   English   中英

如何從文本文件的下一行讀取內容並暫停,以便稍后再從該行讀取內容?

[英]How can I read from the next line of a text file, and pause, allowing me to read from the line after that later?

我編寫了一個程序,根據兩個常數文件,該程序將隨機數生成兩個文本文件,將隨機字母生成第三個字符。 現在,我需要逐行閱讀每個文本文件,並將它們放在一起。 該程序是,在這里找到的建議並不能真正解決我的問題。 當我嘗試這種方法時,它只會讀取所有行,直到完成為止,而不會允許我選擇暫停它,轉到另一個文件等。

理想情況下,我想找到某種方式來僅讀取下一行,然后在此之后轉到下一行。 就像某種變量可以使我在閱讀中占有一席之地。

public static void mergeProductCodesToFile(String prefixFile,
                                           String inlineFile,
                                           String suffixFile,
                                           String productFile) throws IOException 
{
    try (BufferedReader br = new BufferedReader(new FileReader(prefixFile))) 
    {
        String line;
        while ((line = br.readLine()) != null) 
            {
                try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(productFile, true))))
                {
                        out.print(line); //This will print the next digit to the right
                }
            catch (FileNotFoundException e) 
                {
                    System.err.println("File error: " + e.getMessage());
                }  
            }
    }
}

編輯 :根據以下內容創建的數字。 基本上,常量告訴它每行要創建多少個數字,以及要創建多少行。 現在,我需要將這些組合在一起,而不必從兩個文本文件中刪除任何內容。

public static void writeRandomCodesToFile(String codeFile, 
                                          char fromChar, char toChar,
                                          int numberOfCharactersPerCode,
                                          int numberOfCodesToGenerate) throws IOException 
{

    for (int i = 1; i <= PRODUCT_COUNT; i++)
    {
        int I = 0;


        if (codeFile == "inline.txt")
        {

            for (I = 1; I <= CHARACTERS_PER_CODE; I++)
            {
                int digit = (int)(Math.random() * 10);


                try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
                {
                        out.print(digit); //This will print the next digit to the right
                }
                catch (FileNotFoundException e) 
            {
                System.err.println("File error: " + e.getMessage());
                System.exit(1);  
            }

            }
        }

        if ((codeFile == "prefix.txt") || (codeFile == "suffix.txt"))
        {

            for (I = 1; I <= CHARACTERS_PER_CODE; I++)
            {
                Random r = new Random();
                char digit = (char)(r.nextInt(26) + 'a');
                digit = Character.toUpperCase(digit);

                try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
                {
                        out.print(digit);
                }
                catch (FileNotFoundException e) 
            {
                System.err.println("File error: " + e.getMessage());
                System.exit(1);  
            }

            }    
        }
            //This will take the text file to the next line
            if (I >= CHARACTERS_PER_CODE)
            {
                {
                Random r = new Random();
                char digit = (char)(r.nextInt(26) + 'a');

                try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(codeFile, true))))
                {
                        out.println(""); //This will return a new line for the next loop
                }
                catch (FileNotFoundException e) 
            {
                System.err.println("File error: " + e.getMessage());
                System.exit(1);  
            }
                }
            }

    }
    System.out.println(codeFile + " was successfully created.");

}// end writeRandomCodesToFile()

尊重您的代碼,將是這樣的:

public static void mergeProductCodesToFile(String prefixFile, String inlineFile, String suffixFile, String productFile) throws IOException {
    try (BufferedReader prefixReader = new BufferedReader(new FileReader(prefixFile));
        BufferedReader inlineReader = new BufferedReader(new FileReader(inlineFile));
        BufferedReader suffixReader = new BufferedReader(new FileReader(suffixFile))) {

      StringBuilder line = new StringBuilder();
      String prefix, inline, suffix;
      while ((prefix = prefixReader.readLine()) != null) {
        //assuming that nothing fails and the files are equals in # of lines.
        inline = inlineReader.readLine();
        suffix = suffixReader.readLine();
        line.append(prefix).append(inline).append(suffix).append("\r\n");
        // write it
        ...

      }
    } finally {/*close writers*/}
  }

可能會拋出一些異常。

希望您不要以一種方法來實現它。 您也可以使用迭代器,也可以使用非常簡單的閱讀器類(方法)。

我不會使用List來加載數據,至少我保證文件的大小較小,並且可以節省內存使用量。

我們討論的方法是存儲數據並進行交織。 就像塞爾吉奧在回答中所說的那樣,確保就文件大小和數據結構將使用多少內存而言,內存不是問題。

//the main method we're working on
public static void mergeProductCodesToFile(String prefixFile,
                                       String inlineFile,
                                       String suffixFile,
                                       String productFile) throws IOException
{
    try {
        List<String> prefix = read(prefixFile);
        List<String> inline = read(inlineFile);
        List<String> suffix = read(productFile);

        String fileText = interleave(prefix, inline, suffix);
        //write the single string to file however you want
    } catch (...) {...}//do your error handling...
}

//helper methods and some static variables
private static Scanner reader;//I just prefer scanner. Use whatever you want.
private static StringBuilder sb;

private static List<String> read(String filename) throws IOException
{
    List<String> list = new ArrayList<String>;
    try (reader = new Scanner(new File(filename)))
    {
        while(reader.hasNext())
        { list.add(reader.nextLine()); }
    } catch (...) {...}//catch errors...
}

//I'm going to build the whole file in one string, but you could also have this method return one line at a time (something like an iterator) and output it to the file to avoid creating the massive string
private static String interleave(List<String> one, List<String> two, List<String> three)
{
    sb = new StringBuilder();
    for (int i = 0; i < one.size(); i++)//notice no checking on size equality of words or the lists. you might want this
    {
        sb.append(one.get(i)).append(two.get(i)).append(three.get(i)).append("\n");
    }
    return sb.toString()
}

顯然,在內存和性能方面仍有一些需求。 另外,還有一些方法可以使它稍微擴展到其他情況,但這是一個很好的起點。 使用c#,我可以更輕松地利用迭代器使交錯一次為您提供一行,從而可能節省內存。 只是一個不同的想法!

暫無
暫無

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

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