繁体   English   中英

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

[英]Reading and modifying the text from the text file in 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);
        }
    }
}

我为您编写了一种快速方法,我认为您可以做您想做的事,即删除一行中所有出现的令牌,该令牌被嵌入行中并由前导破折号标识。

该方法在编辑令牌后读取文件并将其直接写到文件中。 这将使您能够处理巨大的文件而不必担心内存限制。

您可以在成功编辑后简单地重命名输出文件。 我将由您自己解决。

如果您确实必须在内存管理中使用字符串缓冲区,请从我的方法中获取行编辑的逻辑,然后对其进行修改以与字符串缓冲区一起使用。

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

}

暂无
暂无

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

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