これを行う簡単な方法はわかりませんが、ファイルからテキストを読み取って編集し、編集したテキストでファイルを上書きするという、かなり複雑な方法があります。まず、ファイルを行ごとに配列に読み込む必要があります。
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();
}
}
StringTokenizer
2 番目の質問に答えるには、 を使用して文字列を単語に分割し、新しい単語をテキスト行に挿入することで、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)
これがお役に立てば幸いです。