package Test08;
import java.io.*;
public class test01 {
public void photo() throws IOException {
//获取上传文件的路径,通过file建立数据源的链接
String str = "C:\\Users\\ALIENWARE\\Desktop\\F35-Aircraft-picture-credit_Lockheed-Martin.jpg";
//判断一下链接是否存在,不存在,直接结束
//获取目的地路径,通过file建立链接(目的地)
String str1 = "C:\\Users\\ALIENWARE\\IdeaProjects\\TestEight";
File file = new File(str1);
//判断一下链接是否存在,不存在则创建文件夹
if(!file.exists()){
file.mkdirs();
}
//通过获取文件名称及上传文件的位置,构建新的路径
String filename = str + File.separator + System.currentTimeMillis() + str.substring(str.lastIndexOf("."));
InputStream is = null;
OutputStream os = null;
//获取输入输出流
try {
is = new FileInputStream(str);
os = new FileOutputStream(filename);
} catch (FileNotFoundException e){
e.fillInStackTrace();
}
//具体的上传操作
byte[] bytes = new byte[1024];
int temp = 0;
while ((temp = is.read(bytes)) != -1){
os.write(bytes, 0, temp);
}
os.close();
is.close();
}
public static void main(String[] args) throws IOException {
test01 test1 = new test01();
test1.photo();
}
}
应该是str和filename指向的是同一个文件导致的错误,我在eclipse里打印str的值后发现str和值和filename的值一样,把给filename赋值的str改为str1程序就正常运行了。
import java.io.*;
public class test01 {
public void photo() throws IOException {
//获取上传文件的路径,通过file建立数据源的链接
String str = "f:\\F35-Aircraft-picture-credit_Lockheed-Martin.jpg";
//判断一下链接是否存在,不存在,直接结束
//获取目的地路径,通过file建立链接(目的地)
String str1 = "f:\\TestEight";
File file = new File(str1);
//判断一下链接是否存在,不存在则创建文件夹
if(!file.exists()){
file.mkdirs();
}
//通过获取文件名称及上传文件的位置,构建新的路径
String filename = str1 + File.separator + System.currentTimeMillis() + str.substring(str.lastIndexOf("."));
// System.out.println("str="+str);
InputStream is = null;
OutputStream os = null;
//获取输入输出流
try {
is = new FileInputStream(str);
os = new FileOutputStream(filename);
} catch (FileNotFoundException e){
e.fillInStackTrace();
}
//具体的上传操作
byte[] bytes = new byte[1024];
int temp = 0;
while ((temp = is.read(bytes)) != -1){
os.write(bytes, 0, temp);
}
os.close();
is.close();
}
public static void main(String[] args) throws IOException {
test01 test1 = new test01();
test1.photo();
}
}