0

我想这归结为读取和写入同一个文件。我希望能够返回与输入相同的文本文件,但所有整数值都翻了两番。我是否应该尝试使用 Java 进行此操作,还是写入新文件并覆盖原始 .txt 文件更好?

从本质上讲,我正在尝试改变这个:

12
fish
55 10 yellow 3

进入这个:

48
fish
220 40 yellow 12

这是我到目前为止所得到的。目前,它不会修改 .txt 文件。

import java.io.*;
import java.util.Scanner;

public class CharacterStretcher 
{
public static void main(String[] args)
{
    Scanner keyboard = new Scanner( System.in );
    System.out.println("Copy and paste the path of the file to fix");
    // get which file you want to read and write
    File file = new File(keyboard.next());
    File file2 = new File("temp.txt");
    BufferedReader reader;
    BufferedWriter writer;
    try {
        // new a writer and point the writer to the file
        FileInputStream fstream = new FileInputStream(file);
        // Use DataInputStream to read binary NOT text.
        reader = new BufferedReader(new InputStreamReader(fstream));
        writer = new BufferedWriter(new FileWriter(file2, true));

        String line = "";
        String temp = "";
        int var = 0;
        int start = 0;
        System.out.println("000");
        while ((line = reader.readLine()) != null) 
        {
            System.out.println("a");
            if(line.contains("="))
            {
                System.out.println("b");
                var = 0;
                temp = line.substring(line.indexOf('='));
                for(int x = 0; x < temp.length(); x++)
                {
                    System.out.println(temp.charAt(x));
                    if(temp.charAt(x)>47 && temp.charAt(x)<58)  //if 0<=char<=9 
                    {
                        if(start==0)
                            start = x;
                        var*=10;
                        var+=temp.indexOf(x)-48;    //converts back into single digit
                    }
                    else
                    {
                        if(start!=0)
                        {
                            temp = temp.substring(0, start) + var*4 + temp.substring(x);
                            //writer.write(line.substring(0, line.indexOf('=')) + temp);
                            //TODO:  Currently writes a bunch of garbage to the end of the file, how to write in the middle?
                        //move x if var*4 has an extra digit
                            if((var<10 && var>2)
                                    || (var<100 && var>24)
                                    || (var<1000 && var>249)
                                    || (var<10000 && var>2499))
                                x++;
                        }
                        //start = 0;
                    }
                    System.out.println(temp + " " + start);
                }
                if(start==0)
                    writer.write(line);
                else
                    writer.write(temp);

            }
        }
        System.out.println("end");
        // writer the content to the file
        //writer.write("I write something to a file.");

        // always remember to close the writer
        writer.close();
        //writer = null;
        file2.renameTo(file); //TODO: Not sure if this works...
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

4

3 回答 3

4

鉴于这是对格式化文本文件的快速简单的破解,我认为你不需要太聪明。

您决定是否查看数字的逻辑非常复杂,我会说这是矫枉过正。

我已经写了一个基本大纲,说明我在这种情况下要做什么。这不是很聪明或令人印象深刻,但我认为应该完成工作。我省略了覆盖和读取控制台输入的内容,因此您可以自己进行一些实现;-)

import java.io.*;

public class CharacterStretcher {

    public static void main(String[] args) {

        //Assumes the input is at c:\data.txt
        File inputFile = new File("c:\\data.txt");
        //Assumes the output is at c:\temp.txt
        File outputFile = new File("c:\\temp.txt");
        try {
            //Construct a file reader and writer
            final FileInputStream fstream = new FileInputStream(inputFile);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
            final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));

            //Read the file line by line...
            String line;
            while ((line = reader.readLine()) != null) {
                //Create a StringBuilder to build our modified lines that will
                //go into the output file
                StringBuilder newLine = new StringBuilder();

                //Split each line from the input file by spaces
                String[] parts = line.split(" ");

                //For each part of the input line, check if it's a number
                for (String part : parts) {
                    try {
                        //If we can parse the part as an integer, we assume
                        //it's a number because it almost certainly is!
                        int number = Integer.parseInt(part);
                        //We add this to out new line, but multiply it by 4
                        newLine.append(String.valueOf(number * 4));
                    } catch (NumberFormatException nfEx) {
                        //If we couldn't parse it as an integer, we just add it
                        //to the new line - it's going to be a String.
                        newLine.append(part);
                    }

                    //Add a space between each part on the new line
                    newLine.append(" ");
                }
                //Write the new line to the output file remembering to chop the
                //trailing space off the end, and remembering to add the line
                //breaks
                writer.append(newLine.toString().substring(0, newLine.toString().length() - 1) + "\r\n");
                writer.flush();
            }

            //Close the file handles.
            reader.close();
            writer.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
于 2013-03-12T17:17:51.017 回答
3

您可能需要考虑其中之一:

  1. 在内存中构建新文件,而不是尝试写入您正在读取的同一文件。你可以用StringBuilder这个。

  2. 写入一个新文件,然后用新文件覆盖旧文件。这个 SO Question可以帮助你。

使用这两者,您将能够看到与输入文件分开的整个输出。此外,使用选项 (2),您不会有操作在中间失败并给您带来混乱文件的风险。

现在,您当然可以就地修改文件。但对于您的情况来说,这似乎是不必要的复杂性,除非您有非常大的输入文件。

至少,如果您首先尝试这种方式,您可以缩小更复杂版本失败的原因。

于 2013-03-12T16:45:01.727 回答
0

您不能同时读取和写入同一个文件,因为这会修改您当前阅读的文本。这意味着,您必须首先编写修改后的新文件,然后将其重命名为原始文件。您可能需要在重命名之前删除原始文件。

对于重命名,您可以使用File.renameTo或查看许多 SO 的问题之一

您似乎通过收集单个数字并将它们相加来解析代码中的整数。您应该考虑使用 aScanner.nextInt或employ Integer.parseInt

您可以逐行读取文件,在空白处拆分单词,然后解析它们并检查它是整数还是其他单词。

于 2013-03-12T16:45:19.990 回答