java - 如何将文本文件中的整数值变为四倍?

标签 java

我想这可以归结为读取和写入同一个文件。我希望能够返回与输入相同的文本文件,但所有整数值都增加四倍。我是否应该使用 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();
    }
}

}

最佳答案

鉴于这是对格式化文本文件的一种非常快速且简单的破解,我认为您不需要对此太聪明。

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

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

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();
        }
    }
}

关于java - 如何将文本文件中的整数值变为四倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366655/

相关文章:

java - Guava 缓存允许陈旧读取吗?

java - 如何返回两个整数

java - 无法解析项目 : Android library and Java library module dependency

使用 TransportCilent 的 Java ElasticSearch 示例

java - 类型 Response.Response 构建器不可见

java - 各种Array复制方法的区别

java - 如何使用 JAXB 解码 XML。特殊案例

java - JAVA中通过OTAClient在QC的测试集中添加测试对象

java - 如何通过不获取另一个案例的值来在 switch case 中创建 if 语句?

java - 设置 BorderLayout 并调用 PaintComponent()