package com.machine.study;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JFileChooser;
public class SystemRead {
String currentPath;
String currentFilePath;
File selectFile;
JFileChooser fileChoorser =new JFileChooser();//文件选择器
public SystemRead() throws FileNotFoundException, IOException{
int option =fileChoorser.showDialog(null, null);//显示文件选取的对话框
selectFile= fileChoorser.getSelectedFile(); //获取选择文件的路径
currentPath =System.getProperty("user.dir");//user.dir指定了当前的路径
currentFilePath=currentPath+"\\data"; //得到当前文件夹的路径,当前工程下有个data文件夹想把文件复制到data中
System.out.println(selectFile);
System.out.println(currentFilePath);
copyFile(selectFile, currentFilePath);
}
public void copyFile(File oldFile, String newPath) throws FileNotFoundException,IOException {
try {
int bytesum = 0;
int byteread = 0;
if (oldFile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldFile); //读入原文件
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) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
new SystemRead();
}
}
程序错误为:
java.io.FileNotFoundException: C:\Documents and Settings\康明轩\workspace\机器学习和测试\data (拒绝访问。)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:179)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at com.machine.study.SystemRead.copyFile(SystemRead.java:36)
at com.machine.study.SystemRead.<init>(SystemRead.java:25)
at com.machine.study.SystemRead.main(SystemRead.java:54)
D:\model_r.txt
C:\Documents and Settings\康明轩\workspace\机器学习和测试\data
复制单个文件操作出错
------解决思路----------------------
仔细看看错误信息就明白了,新路径是个文件夹的路径?
------解决思路----------------------
1、一般用于文件名称不取中名;2、首先建立文件目录,再创建文件,再复制文件内容。