你能解释为什么我的2方法mergeFile()和mergeData()不起作用,当我运行它给我一个空白的文本文件。我真的不明白为什么.....这是我的代码:
String dirName, fileName;
public MergeFile(String dirName, String fileName){
this.dirName = dirName;
this.fileName = fileName;
}
public static void main(String [] args){
MergeFile mf = new MergeFile("C:\\Users\\Shine\\Desktop", "C:\\Users\\Shine\\Desktop\\trung.txt");
mf.mergeData();
}
public void mergeData(){
for (int i = 0; i < createData().size(); i++){
FileReader fr;
BufferedReader br;
FileWriter fw;
BufferedWriter bw = null;
try{
fr = new FileReader(createData().get(i));
br = new BufferedReader(fr);
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
String line;
while ((line = br.readLine()) != null){
bw.write(line);
}
br.close();
}catch(IOException exp){
exp.printStackTrace();
}finally{
try {
if (bw != null){
bw.flush();
bw.close();
}
}catch(IOException exp){
exp.printStackTrace();
}
}
}
}
我的createData方法:
public ArrayList<File> createData(){
File directory = new File(dirName);
ArrayList<File> file = new ArrayList<>();
if (directory.isDirectory()){
for (int i = 0; i < directory.listFiles().length; i++){
if (directory.listFiles()[i].getName().endsWith(".txt")){
file.add(directory.listFiles()[i]);
}
}
return file;
}else{
return null;
}
}
我的mergeFile方法:
public void mergeFile(){
for (int i = 0; i < createData().size(); i++){
try{
FileInputStream fis = new FileInputStream(createData().get(i));
FileOutputStream fos = new FileOutputStream(fileName);
int counter;
while((counter = fis.read()) != -1){
System.out.println(counter);
//fos.write(counter);
}
fos.flush();
fos.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
}
答案 0 :(得分:0)
移动声明
FileReader fr;
BufferedReader br;
FileWriter fw;
BufferedWriter bw = null;
在循环之外。
答案 1 :(得分:0)
在写入函数
之后,在循环内部使用flush()
函数