按照网上的方法执行 file.delete() 时,始终返回失败
源码如下
package tpy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
new readTXTtest().readData("D:\\abc\\");
}
public ArrayList<String[]> readData(String receivedPath) {
// TODO Auto-generated method stub
ArrayList<String[]> datalist = new ArrayList<String[]>();
String errorPath = null;
String backupPath = null;
File readFile = null;
FileInputStream inputstream = null;
FileOutputStream outputstream = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
String[] inFileNames = null;
try {
inFileNames = new File(receivedPath).list();
//如果文件夹下有多个文件 逐个读取,添加到返回结果集中
for (String filename : inFileNames) {
String filePath = receivedPath + filename;
readFile = new File(filePath);
Scanner infile = new Scanner(readFile);
String[] splitedData = null;
while (infile.hasNextLine()) {
String str = infile.nextLine();
if (str.length() > 0) {
splitedData = splitstr(str);
datalist.add(splitedData);
}
}
File newtxt = new File(backupPath + readFile.getName());
FileWriter fw = new FileWriter(newtxt);
fw.write("");
fw.close();
inputstream = new FileInputStream(readFile);
inChannel = inputstream.getChannel();
outputstream = new FileOutputStream(new File(backupPath + readFile.getName()));
outChannel = outputstream.getChannel();
outChannel.transferFrom(inChannel, 0, inChannel.size());
inChannel.close();
inputstream.close();
outChannel.close();
outputstream.close();
infile.close();
System.out.println(infile);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
for (int i = 0; i < inFileNames.length; i ++){
//new File(receivedPath + inFileNames[i]).renameTo(new File(receivedPath + inFileNames[i] + ".over"));
boolean a = deletefile(new File(receivedPath + inFileNames[i]));
System.out.println(a);
}
return datalist;
}
/*
* 根据 指定符号拆分TXT文档中的内容
* @param str 输入的内容
* @return 将拆分后的内容作为数组返回
*/
public static String[] splitstr(String str) {
String strr = str.trim();
String[] abc = strr.split("\\|");
return abc;
}
private boolean deletefile(File srcFile){
return srcFile.getAbsoluteFile().delete();
}
}
在执行删除命令时,怎么都是返回false。
后来在网上找了下,提示需要关闭输入输出流,添加后还是不行
最后才发现需要把Scanner类也关掉才行。
注意:在循环内部创建的赋值/创建的流、Scanner,那么相应的流和Scanner都需要在循环内部进行关闭。否则一旦脱离循环,将会有部分没使用的堆内存存在在堆内存中,在代码没有执行完成前不会被回收,导致占用文件,最终导致更名/删除等操作失败。