gpt4 book ai didi

java - 列出文件夹中的所有 txt 文件,并在所有 txt 文件中的一行添加字符串

转载 作者:行者123 更新时间:2023-11-30 06:12:38 25 4
gpt4 key购买 nike

我正在尝试列出目录中的所有txt文件,逐个读取txt文件并在同一txt文件中编辑一行。继续对所有其他 txt 文件执行相同操作。当我尝试以下代码时,我的 txt 文件变为空白。请帮忙。

import java.io.File;
import java.util.ArrayList;
import java.io.*;

public class MainClass {

public static void main(String[] args) throws IOException {
String s = null;
ArrayList<String> lines = new ArrayList<String>();
String dir = "C:\\Users\\ME\\Desktop\\XX";
String line = null;
File folder = new File(dir);
String[] files = folder.list();
for (String file : files) {
try {
File f = new File(dir + "\\" + file);
if (file.endsWith(".ind")) {
FileReader fileReader = new FileReader(f);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
line = bufferedReader.readLine();
while ((bufferedReader.readLine()) != null) {
if (line.contains("GROUP_FILENAME:"))
s = line.substring(0, 15) + "/HOME/FOLDER/" + line.substring(15);
lines.add(s);
System.out.println(s);
}
fileReader.close();
bufferedReader.close();
FileWriter fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);
for (String st : lines)
out.write(st);
out.flush();
out.close();

}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + "'");
}
}
}
}

最佳答案

这里有一个细微的变化,希望这会起作用。

 import java.io.File;
import java.util.ArrayList;
import java.io.*;
public class MainClass
{
public static void main(String[] args) throws IOException
{
String s = null;
ArrayList<String> lines = new ArrayList<String>();
String dir = "C:\\Users\\ME\\Desktop\\XX" ;
String line = null;
File folder = new File(dir);
String[] files = folder.list();
for (String file : files)
{
try {
File f = new File(dir + "\\" +file);
if (file.endsWith(".ind")){
FileReader fileReader = new FileReader(f);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
// line = bufferedReader.readLine();
while((line = bufferedReader.readLine()) != null) {
if ( line.contains("GROUP_FILENAME:"))
s = line.substring(0, 15) + "/HOME/FOLDER/" + line.substring(15);
lines.add(s);
System.out.println(s);
}
fileReader.close();
bufferedReader.close();
FileWriter fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);
for(String st : lines)
out.write(st);
out.flush();
out.close();

}
}
catch(FileNotFoundException ex) {
System.out.println( "Unable to open file '" + "'");
}
}
}
}

关于java - 列出文件夹中的所有 txt 文件,并在所有 txt 文件中的一行添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49898259/

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