简体   繁体   English

从文件中读取并在java中写入文件

[英]reading from the file and writing to the file in java

I am beginner with Java. 我是Java的初学者。

This is my approach: 这是我的方法:

I am trying to read two files and then get the union of them. 我试图读取两个文件,然后得到它们的联合。 I should am using an array with size 100. (just one array allowed, reading and writing line by line or arrayList or other structures are not allowed.) 我应该使用大小为100的数组。(只允许一个array不允许逐行读取和写入,或者arrayList或其他结构。)

First, I read all records from file1 , and write them to the output, a third file. 首先,我从file1读取所有记录,并将它们写入输出,第三个文件。 For that purpose, I read 100 record at a time, and write them to the third file using iteration. 为此,我一次读取100条记录,并使用迭代将它们写入第三个文件。

After that, like first file, this time I read second file as 100 records at a time, and write them to the memory[] . 之后,就像第一个文件一样,这次我一次读取第二个文件为100条记录,并将它们写入memory[] Then I find the common records, if the record which I read from File2 is not in File1, I write it to the output file. 然后我找到了常见的记录,如果我从File2读取的记录不在File1中,我将其写入输出文件。 I do this until reader2.readLine() gets null and I re-open file1 in each iteration. 我这样做直到reader2.readLine()得到null并且我在每次迭代中重新打开file1

This is what I have done so far, almost done. 这是我到目前为止所做的,差不多完成了。 Any help would be appreciated. 任何帮助,将不胜感激。

Edit: ok, now it doesn't give any exception, but it can't find the different records and can't write them. 编辑:好的,现在它不会给出任何异常,但它找不到不同的记录而无法写入它们。 I guess the last for loop and booleans don't work , why? 我想循环和布尔的最后一个不起作用,为什么? I really need help. 我真的需要帮助。 Thanks for your patience. 谢谢你的耐心。

import java.io.*;

public class FileUnion
{
private static long startTime, endTime;

public static void main(String[] args) throws IOException 
{
    System.out.println("PROCESSING...");
    reset();
    startTimer();

    String[] memory = new String[100];
    int memorySize = memory.length;

    File file1 = new File("stdlist1.txt");
    BufferedReader reader1 = new BufferedReader(new FileReader(file1));

    File file3 = new File("union.txt");
    BufferedWriter writer = new BufferedWriter(new FileWriter(file3));

    int numberOfLinesFile1 = 0;
    String line1 = null;
    String line11 = null;


    while((line1 = reader1.readLine()) != null)
    {
        for (int i = 0; i < memorySize; )
        {
            memory[i] = line1;
            i++;

            if(i < memorySize)
            {
                line1 = reader1.readLine();
            }
        }

        for (int i = 0; i < memorySize; i++)
        {
            writer.write(memory[i]);
            writer.newLine();
            numberOfLinesFile1++;
        }
    }

    reader1.close();

    File file2 = new File("stdlist2.txt");
    BufferedReader reader2 = new BufferedReader(new FileReader(file2));

    String line2 = null;
    while((line2 = reader2.readLine()) != null)
    {
        for (int i = 0; i < memorySize; )
        {
            memory[i] = line2;
            i++;

            if(i < memorySize)
            {
                line2 = reader2.readLine();
            }
        }

        for (int k = 0; k < memorySize; k++ )
        {
            boolean found = false;
            File f1 = new File("stdlist1.txt");
            BufferedReader buff1 = new BufferedReader(new FileReader(f1));

            for (int m = 0; m < numberOfLinesFile1; m++)
            {
                line11 = buff1.readLine();

                if (line11.equals(memory[k]) && found == false);
                {
                    found = true;
                }

            }
            buff1.close();

            if (found == false)
            {
                writer.write(memory[k]);
                writer.newLine();
            }


        }       
    }

    reader2.close();
    writer.close();

    endTimer();
    long time = duration();
    System.out.println("PROCESS COMPLETED SUCCESSFULLY");
    System.out.println("Duration: " + time + " ms");

}

public static void startTimer()
{
    startTime = System.currentTimeMillis();
}
public static void endTimer()
{
    endTime = System.currentTimeMillis();
}
public static long duration()
{
    return endTime - startTime;
}
public static void reset()
{
    startTime = 0;
    endTime = 0;
}
}

EDIT! 编辑! Redo. 重做。

Ok, so to use 100 lines at a time you need to check for null, otherwise trying to write null to a file could cause errors. 好吧,所以要一次使用100行,你需要检查null,否则尝试将null写入文件可能会导致错误。

You are checking if the file is at the end once, and then gathering 99 more peices of info without checking for null. 您正在检查文件是否在最后一次,然后收集99个更多的信息,而不检查null。

What if when this line is called: 如果调用此行,该怎么办:

while((line2 = reader2.readLine()) != null)

there is only 1 line left in the file? 文件中只剩下1行? Then your memory array contains 99 instances of null, and you try to write null to the file 99 times. 然后你的内存数组包含99个null实例,并尝试将99写入该文件的null。 That's worse case scenario. 那是更糟糕的情况。

I don't really know how much help we are supposed to give to people looking for homework help, on most sites I'm familiar with it's not even allowed. 我真的不知道我们应该给寻求家庭作业帮助的人多少帮助,在大多数我熟悉的网站上甚至都不允许。

here is an example of one way to write the first file. 这是编写第一个文件的一种方法的示例。

String line1 = reader1.readLine();

boolean end_of_file1 = false;
while(!end_of_file)
{
    for (int i = 0; i < memorySize)
    {
        memory[i] = line1;
        i++;

        if(i < memorySize)
        {
            if((line1 = reader1.readLine()) == null)
            {
                end_of_file1 = true;
            }
        }
    }

    for (int i = 0; i < memorySize; i++)
    {
        if(!memory[i] == null)
        {
            writer.write(memory[i]);
            writer.newLine();
            numberOfLinesFile1++;
        }
    }
}

reader1.close();

once you have that, to make the checking for copies easier, make a public static boolean that checks the file for it, then you can call that, it will make the code cleaner. 一旦你有了这个,为了更容易检查副本,制作一个公共静态布尔值来检查文件,然后你可以调用它,它会使代码更清晰。

public static boolean isUsed(String f1, String item, int dist)
{
    BufferedReader buff1 = new BufferedReader(new FileReader(f1));

    for(int i = 0;i<dist;i++)
    {
        String line = buff1.readLine()
        if(line == null){
            return false;
        }
        if(line.equals(item))
        {
            return true;
        }
    }
    return false;
}

Then use the same method as writing file 1, only before writing each line check to see if !isUsed() 然后使用与写入文件1相同的方法,仅在写入每行检查之前查看是否!isUsed()

boolean end_of_file2 = false;
memory = new String[memorySize];// Reset the memory, erase old data from file1
int numberOfLinesFile2=0;
String line2 = reader2.readLine();
while(!end_of_file2)
{
    for (int i = 0; i < memorySize; )
    {
        memory[i] = line2;
        i++;

        if(i < memorySize)
        {
            if((line2 = reader2.readLine()) == null)
            {
                end_of_file2 = true;
            }
        }
    }

    for (int i = 0; i < memorySize; i++)
    {
        if(!memory[i] == null)
        {
            //Check is current item was used in file 1.
            if(!isUsed(file1, memory[i], numberOfLinesFile1)){//If not used already
                writer.write(memory[i]);
                writer.newLine();
                numberOfLinesFile2++;
            }
        }
    }
}
reader2.close();
writer.close();

Hope this helps. 希望这可以帮助。 Notice I'm not supplying the full code, because I've learned that just pasting the code will make it more likely for copy and paste to just use a code without understanding it. 请注意,我没有提供完整的代码,因为我已经了解到只是粘贴代码会使复制和粘贴更有可能只使用代码而不理解它。 I hope you find it useful. 希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM