在JAVA中的一行文件末尾添加一个特定的字符串

时间:2012-08-31 14:09:50

标签: java string file line add

我的问题是,我猜,非常简单:

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

Ex,给定 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

提前感谢您的帮助。

2 个答案:

答案 0 :(得分: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()返回String中的下一个单词。以下是您的问题中指定结果的示例:

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)

我希望这对你有用!

答案 1 :(得分: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);

简单就是那个

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

    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 
        }
    }

参考: