0

私の質問は、かなり単純だと思います。

1つの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()テキスト ファイルを読み取った後、 2 つの文字列を結合するメソッドを使用して、文字列に対して何かを行う必要があります。このコードは、質問の例を実行します。

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

StringTokenizer2 番目の質問に答えるには、 を使用して文字列を単語に分割し、新しい単語をテキスト行に挿入することで、1 つまたは複数の単語を行に挿入できます。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 に答える