gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:01:12 24 4
gpt4 key购买 nike

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

给定一个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

预先感谢您的帮助。

最佳答案

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

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)

希望这对您有用!

关于java - JAVA中在文件的一行末尾添加特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12217087/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com