我正在尝试列出目录中的所有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 '" + "'");
}
}
}
}
答案 0 :(得分:1)
这是一个小小的改变,希望这会奏效。
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 '" + "'");
}
}
}
}