在Java中读取和修改文本文件中的文本

时间:2015-06-22 09:29:50

标签: java

我有一个需要修改文本文件中某些文本的项目。 像BB,BO,BR,BZ,CL,VE-BR 我需要让它成为BB,BO,BZ,CL,VE。 和HU,LT,LV,UA,PT-PT / AR成为HU,LT,LV,UA,/ AR。

我尝试输入一些代码,但代码无法循环,在这种情况下也是如此。

IN / CI,GH,KE,NA,NG,SH,ZW / EE,HU,LT,LV,UA,/ AR,BB

" AR,BB,BO,BR,BZ,CL,CO,CR,CW,DM,DO,VE-AR-BR-MX"

我想删除第二行中的AR,但它只删除第一行中的AR。 我不知道并寻求帮助。 请

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;

public class tomy {
    static StringBuffer stringBufferOfData = new StringBuffer();
    static StringBuffer stringBufferOfData1 = stringBufferOfData;
    static String filename = null;
    static String input = null;
    static String s = "-";
    static Scanner sc = new Scanner(s);

    public static void main(String[] args) {
        boolean fileRead = readFile();
        if (fileRead) {
            replacement();
            writeToFile();
        }
        System.exit(0);
    }

    private static boolean readFile() {
        System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
        filename = "C:\\test.txt";
        Scanner fileToRead = null;
        try {
            fileToRead = new Scanner(new File(filename));

            for (String line; fileToRead.hasNextLine()
                    && (line = fileToRead.nextLine()) != null;) {
                System.out.println(line);
                stringBufferOfData.append(line).append("\r\n");
            }
            fileToRead.close();
            return true;
        } catch (FileNotFoundException ex) {
            System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
            return false;
        } finally {
            fileToRead.close();
            return true;
        }
    }

    private static void writeToFile() {
        try {
            BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
                    filename));
            bufwriter.write(stringBufferOfData.toString());

            bufwriter.close();
        } catch (Exception e) {// if an exception occurs
            System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
        }
    }

    private static void replacement() {
        System.out.println("Please enter the contents of a line you would like to edit: ");

        String lineToEdit = sc.nextLine();

        int startIndex = stringBufferOfData.indexOf(lineToEdit);
        int endIndex = startIndex + lineToEdit.length() + 2;
        String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);

        String data = " ";
        Scanner sc1 = new Scanner(getdata);
        Scanner sc2 = new Scanner(data);
        String lineToEdit1 = sc1.nextLine();
        String replacementText1 = sc2.nextLine();
        int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
        int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
        boolean test = lineToEdit.contains(getdata);
        boolean testh = lineToEdit.contains("-");
        System.out.println(startIndex);

        if (testh = true) {
            stringBufferOfData.replace(startIndex, endIndex, replacementText1);

            stringBufferOfData.replace(startIndex1, endIndex1 - 2,
                    replacementText1);

            System.out.println("Here is the new edited text:\n"
                    + stringBufferOfData);

        } else {
            System.out.println("nth" + stringBufferOfData);

            System.out.println(getdata);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我为你写了一个快速的方法,我认为你做了你想做的事,即删除一行中所有出现的令牌,其中该令牌嵌入在行中并由前导短划线识别。

该方法在编辑令牌后读取文件并将其直接写入文件。这将允许您处理一个巨大的文件,而不必担心内存限制。

成功编辑后,您只需重命名输出文件即可。我会留给你解决这个问题。

如果你觉得你真的必须在内存管理中使用字符串缓冲区,那么从我的方法中获取行编辑的逻辑并修改它以使用字符串缓冲区。

static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
    // the input file
    Scanner inputScanner = null;
    // output file
    FileWriter outputWriter = null;

    try
    {
        // open the input file
        inputScanner = new Scanner(new File(inputFilePath));
        // open output file
        File outputFile = new File(outputPath);
        outputFile.createNewFile();
        outputWriter = new FileWriter(outputFile);

        try
        {

            for (
                    String lineToEdit = inputScanner.nextLine();
                    /*
                     * NOTE: when this loop attempts to read beyond EOF it will throw the
                     * java.util.NoSuchElementException exception which is caught in the
                     * containing try/catch block.
                     * 
                     *  As such there is NO predicate required for this loop.
                    */;
                    lineToEdit = inputScanner.nextLine()
                )
                // scan all lines from input file
            {
                System.out.println("START LINE [" + lineToEdit + "]");

                // get position of dash in line
                int dashInLinePosition = lineToEdit.indexOf('-');

                while (dashInLinePosition != -1)
                    // this line has needs editing
                {

                    // split line on dash
                    String halfLeft = lineToEdit.substring(0, dashInLinePosition);
                    String halfRight = lineToEdit.substring(dashInLinePosition + 1);
                    // get token after dash that is to be removed from whole line
                    String tokenToRemove = halfRight.substring(0, 2);
                    // reconstruct line from the 2 halves without the dash
                    StringBuilder sb = new StringBuilder(halfLeft);
                    sb.append(halfRight.substring(0));

                    lineToEdit = sb.toString();

                    // get position of first token in line
                    int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);

                    while (tokenInLinePosition != -1)
                        // do for all tokens in line
                    {
                        // split line around token to be removed
                        String partLeft = lineToEdit.substring(0, tokenInLinePosition);
                        String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());

                        if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
                            // remove prefix comma from right part
                        {
                            partRight = partRight.substring(1);
                        }

                        // reconstruct line from the left and right parts
                        sb.setLength(0);
                        sb = new StringBuilder(partLeft);
                        sb.append(partRight);
                        lineToEdit = sb.toString();

                        // find next token to be removed from line
                        tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
                    }

                    // handle additional dashes in line
                    dashInLinePosition = lineToEdit.indexOf('-');
                }

                System.out.println("FINAL LINE [" + lineToEdit + "]");

                // write line to output file
                outputWriter.write(lineToEdit);
                outputWriter.write("\r\n");
            }

        }
        catch (java.util.NoSuchElementException e)
            // end of scan
        {
        }
        finally
            // housekeeping
        {
            outputWriter.close();
            inputScanner.close();
        }

    }
    catch(FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch(IOException e)
    {
        inputScanner.close();

        e.printStackTrace();
    }

}