找出指定盘中的word文档并将其复制到指定的文件目录中?-->急需解决期望大家能给出满意的解答-----------------》谢谢
问题:当str赋不同的值结果不一样。其中有三种结果1、复制文件能成功,达到了预想的目的2、抛出NullPointerException 3、抛出java.lang.StringIndexOutOfBoundsException: String index out of range: -1
据我了解第二种异常好像是涉及到文件系统权限。
期望大家能给出满意的解答-----------------》谢谢
源文件:
//程序功能:找出指定盘中的word文档并将其复制到指定的文件目录中
import java.io.*;
public class Test14 {
public static void main(String[] args) throws Exception {
String str = "F:"; //输入不同的值,有不同的结果。这是出问题的地方
copyTest(str);
}
public static void copyTest(String str) throws Exception { //递归实现文件系统列表
File f = new File(str);
String[] li = null;
if (f.isDirectory()) { //是目录的话
li = f.list();
for (int i = 0; i < li.length; i++) {
copyTest(str + "\\" + li[i]); //递归调用
}
}
else { //是文件的话
int i = str.indexOf("."); //找到点分隔符的位置
String str1 = str.substring(i);//取出后缀名
if (str1.equals(".doc")) { //判断文件是否是以.doc结尾的文件
File f2 = new File(str); //以源文件构造一个文件对象
String name = f2.getName(); //取得文件名字
File f1 = new File("d:\\123" + name); //复制文件到D:\123中
InputStream in = new FileInputStream(f2); //输入流
OutputStream out = new FileOutputStream(f1); //输出流
int ch = 0;
while ((ch = in.read()) != -1) { //写入到文件中去
out.write((char) ch);
}
}
}
}
}
----------------解决方案--------------------------------------------------------
建议你用exists()方法判断下,
复制可以这样写
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //文件存在时 , 这个方法不能少,你抛空指针,很有可能是文件夹不存在或者路径不正确
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
----------------解决方案--------------------------------------------------------
回复 2楼 流星雨
我输入的路径都是确保文件存在的,而且也测试过几个,有的能成功,有的不能成功(像我说的那三种情况); ----------------解决方案--------------------------------------------------------