Вопрос о копировании текстового файла в Java - PullRequest
1 голос
/ 01 августа 2011

поэтому с этим фрагментом кода, который я написал, мне было интересно, почему я не получаю желаемый тип вывода ...

//Method to copy over a file to a new file using a delimiter and breaking up the file if it is more than 15 images
    public static void copyFile(File extractedInfo) 
    {
        try
        {
            //Counter to track the # of images/lines
            int c = 0;

            File inputFile = extractedInfo;
            File outputFile = new File(extractedInfo.getParentFile() + "/Extracted Info " + index2++ + ".txt");

            Scanner reader = new Scanner(inputFile);
            reader.useDelimiter("null(U) ");
            BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));

            //While there is a next line...
            while (reader.hasNextLine())
            {
                //If the document has 15 images, create a new file to write to
                if (c%15 == 0)
                {
                    writer.close();
                outputFile = new File(extractedInfo.getParentFile() + "/Extracted Info " + ((index2++) + 1) + ".txt");
                writer = new BufferedWriter(new FileWriter(outputFile));
                }
                //Else, normally, just write out each individual character from the original file.
                writer.append(reader.next());
                c++;
            }

            reader.close();
            writer.close();
        }
        catch (Exception e)
        {
            e.printStackTrace(System.out);
        }
    }

Исходный файл по сути выглядит так ...

C:\Documents and Settings\workspace\Extracted Items\image2.jpeg;image0;null(U) keyword1, keyword2, keyword3, keyword4,
C:\Documents and Settings\workspace\Extracted Items\image3.jpeg;image1;null(U) keyword1, keyword2, keyword3, keyword4,
C:\Documents and Settings\workspace\Extracted Items\image4.jpeg;image2;null(U) keyword1, keyword2, keyword3, keyword4,
C:\Documents and Settings\workspace\Extracted Items\image5.jpeg;image3;null(U) keyword1, keyword2, keyword3, keyword4,

Проблема в том, что выходной файл выглядит точно так же, но я хочу, чтобы все было скопировано, КРОМЕ строки null (u) из исходного документа.Мне просто интересно, правильный ли мой код с точки зрения того, что я хочу, и как я должен заново обработать мой разделитель, чтобы игнорировать ссылки на «null (U)» в исходном файле?

Спасибодля любого предложенного ввода.

Ответы [ 3 ]

3 голосов
/ 01 августа 2011

Изменение outputFile в цикле не влияет на writer, вам также необходимо заново создать его в том же if (добавить вторую строку после переназначения); и закройте старого писателя, прежде чем открывать нового.

1 голос
/ 01 августа 2011

Я еще не уверен, что именно вы хотите сделать, но строка

        writer.append(reader.next());

Кажется, есть недостаток.Автор может по-прежнему иметь ссылку на оригинальный выходной файл вместо нового файла.

Итак, вам, возможно, придется сделать:

0 голосов
/ 01 августа 2011

Просто подумал, что выложу этот код на случай, если он может помочь кому-то еще с подобной проблемой.

  //Method to copy over a file to a new file using a delimiter and breaking up the file if it is more than 15 images
        public static void copyFile(File extractedInfo) 
        {
            try
            {
                //Counter to track the # of images/lines
                int c = 0;

                File inputFile = extractedInfo;
                File outputFile = new File(extractedInfo.getParentFile() + "/Extracted Info " + index2 + ".txt");

                Scanner reader = new Scanner(inputFile);
                reader.useDelimiter("null\\(U\\) ");
                BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));

                //While there is a next line...
                while (reader.hasNextLine())
                {
                    //If the document has 15 images, create a new file to write to
                    if (c%15 == 0)
                    {
                        writer.close();
                        outputFile = new File(extractedInfo.getParentFile() + "/Extracted Info " + index2++ + ".txt");
                        writer = new BufferedWriter(new FileWriter(outputFile));

                        writer.append(reader.next());
                        c++;
                    }
                    else
                    {
                        //Else, normally, just write out each individual character from the original file.
                        writer.append(reader.next());
                        c++;
                    }
                }

                reader.close();
                writer.close();
            }
            catch (Exception e)
            {
                e.printStackTrace(System.out);
            }
        }
...