0

我想我的问题很简单:

给定一个data.txt文件,如何在java中逐行添加一些字符串?我不想删除内容,只是在行尾添加一些字符串。你能告诉我一个简单的代码吗?

例如,给定data.txt文件:

aaa bbb ccc
eee fff ggg

运行java程序后的结果:

aaa bbb ccc ddd
eee fff ggg hhh

附加问题:是否有一种简单的方法可以在给定文件的行中“插入”一些字符串?如果是的话,怎么做呢?结果:

aaa 111 bbb ccc
eee fff 222 ggg

预先感谢您的帮助。

4

2 回答 2

4

我不知道有一种简单的方法可以做到这一点,但是有一种相当复杂的方法可以做到这一点,即从文件中读取文本,对其进行编辑,然后用编辑后的文本覆盖文件。首先,您需要将文件逐行读取到数组中:

package addtext;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author Dan300
 */
public class AddText {

    File yourFile = new File("YourFileHere.txt"); //add the name of your file in the brackets
    int numLines; //this will store the number of lines in the file
    String[] lines; //the lines of text that make up the file will be stored here

    public AddText() {
        numLines = getNumberLines(yourFile);
        lines = new String[numLines];//here we set the size of the array to be the same as the number of lines in the file
        for(int count = 0; count < numLines; count++) {
            lines[count] = readLine(count,yourFile);//here we set each string in the array to be each new line of the file
        }

        doSomethingToStrings();
    }

public static void main(String[] args) {
        new AddText();
    }

上面的代码基本上通过调用下面的方法(返回文件中文本的行数)来设置一个数组以包含与文件中的行数一样多的字符串...:

public int getNumberLines(File aFile) {
    int numLines = 0;
    try {

        BufferedReader input =  new BufferedReader(new FileReader(aFile));
            try {
                String line = null;

                while (( line = input.readLine()) != null){ //ReadLine returns the contents of the next line, and returns null at the end of the file.
                    numLines++;
                }
  }
  finally {
    input.close();
  }
}
catch (IOException ex){
  ex.printStackTrace();
}
    return numLines;
}

...然后通过为每一行调用此方法来设置数组以包含文件中的文本:

public String readLine(int lineNumber, File aFile) {
        String lineText = "";
        try {

            BufferedReader input =  new BufferedReader(new FileReader(aFile));
                try {
                     for(int count = 0; count < lineNumber; count++) {
                        input.readLine();  //ReadLine returns the contents of the next line, and returns null at the end of the file.
                     }
                     lineText = input.readLine();
      }
      finally {
        input.close();
      }
    }
    catch (IOException ex){
      ex.printStackTrace();
    }
        return lineText;
    }

阅读完文本文件后,您现在需要使用.concat()将两个字符串连接在一起的方法对字符串做一些事情。此代码将执行问题中的示例:

public void doSomethingToStrings() {
        try {

            lines[0] = lines[0].concat(" ddd"); //this joins the two strings lines[0] and " ddd"

        } catch (ArrayIndexOutOfBoundsException ex) { // I have added a try{}catch{} block so that if there is not as many lines in the file as expected, the code will still continue.

        }
        try {
            lines[1] = lines[1].concat(" hhh");
        } catch (ArrayIndexOutOfBoundsException ex) {

        }



        try {

            writeFile(yourFile);

        } catch (FileNotFoundException ex) {

        } catch (IOException ex) {
            Logger.getLogger(AddText.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

在此之后,它调用writeFile()将数组写入文件的方法。如果您想让代码更灵活,您可能希望添加另一个构造函数来将不同的数组写入文件:

public void writeFile(File aFile) throws FileNotFoundException, IOException {
        if (aFile == null) {
      throw new IllegalArgumentException("File should not be null.");
    }
    if (!aFile.exists()) {
      throw new FileNotFoundException ("File does not exist: " + aFile);
    }
    if (!aFile.isFile()) {
      throw new IllegalArgumentException("Should not be a directory: " + aFile);
    }
    if (!aFile.canWrite()) {
      throw new IllegalArgumentException("File cannot be written: " + aFile);
    }

    BufferedWriter output = new BufferedWriter(new FileWriter(aFile));
    try {
        for(int count = 0; count < numLines; count++) {
            output.write(lines[count]);
            if(count != numLines-1) {// This makes sure that an extra new line is not inserted at the end of the file
                output.newLine();
            }

        }

    }
    finally {
      output.close();
    }
    }

要回答您的第二个问题,可以在一行中插入一个或多个单词,方法是使用StringTokenizer将字符串拆分为单词,然后在文本行中插入一个新单词。StringTokenizer 将字符串拆分为单词,调用 $Tokenizer1.nextToken() 返回字符串中的下一个单词。这是一个示例,其结果在您的问题中指定:

public void doSomethingElseToStrings() {
        try{
        StringTokenizer splitString1 = new StringTokenizer(lines[0]);
        newLines[0] = splitString1.nextToken();
        for(int count=0;count<=splitString1.countTokens();count++) {
            if(count == 0) {
            newLines[0] = newLines[0].concat(" 111");
        }
            newLines[0] = newLines[0].concat(" ");
            newLines[0] = newLines[0].concat(splitString1.nextToken());

        }
        } catch(ArrayIndexOutOfBoundsException ex) {

        }

        try {
        StringTokenizer splitString2 = new StringTokenizer(lines[1]);
        newLines[1] = splitString2.nextToken();
        for(int count=0;count<=splitString2.countTokens();count++) {
            if(count == 1) {
            newLines[1] = newLines[1].concat(" 222");
        }
            newLines[1] = newLines[1].concat(" ");
            newLines[1] = newLines[1].concat(splitString2.nextToken());

        }
        } catch(ArrayIndexOutOfBoundsException ex) {

        }


        try {

            writeFile(yourFile);

        } catch (FileNotFoundException ex) {

        } catch (IOException ex) {
            Logger.getLogger(AddText.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

但是,要使其与其余代码一起使用,您必须编辑这些部分:

public class AddText {  
    String[] newLines; // <<add
    File yourFile = new File("YourFileHere.txt"); //add the name of your file in the brackets
    int numLines; 
    String[] lines; 

public AddText() {
...
//doSomethingToStrings();  <<delete
doSomethingElseToStrings(); //  <<add
}


public void writeFile(File aFile) throws FileNotFoundException, IOException {
...
//output.write(lines[count]); <<delete
output.write(newLines[count]); //  <<add
...
}

使用该doSomethingToStrings()方法更改文件:

aaa bbb ccc
eee fff ggg
(other text)

对此:

aaa bbb ccc ddd
eee fff ggg hhh
(other text remains the same)

使用该doSomethingElseToStrings()方法将文件更改为:

aaa 111 bbb ccc
ddd eee 222 fff
(other text remains the same)

我希望这对你有用!

于 2012-09-01T11:01:16.823 回答
0

以下是使用Guava的方法:

List<String> lines = Files.readLines(new File("myfile.txt"), Charsets.UTF_8);

StringBuilder output = new StringBuilder();

for(String line : lines) {
    String newLine = addNeededStringToLine(line);
    output.append(newLine);
}

Files.write(output, new File("myfile2.txt"), Charsets.UTF_8);

就那么简单

关于插入行,您可以简单地将整行拆分为单独的字符串,然后在它们之间放置要插入的值。使用类似的东西:

    String line = "a b c" ;
    String[] split = line.split(" ");

    for (int i = 0; i < split.length; i++) {
        String string = split[i];
        System.out.println(string);
        if(string.equals("b")) {
            //some insterting 
        }
    }

参考:

于 2012-09-01T11:16:20.497 回答