首先给出代码import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteCopyFile
{
public static void main(String[] args)
{
File f1 = new File( "E:\\Java项目相关代码 ");
File f2 = new File( "D:\\Java项目相关代码 ");
FileInputStream is=null;
FileOutputStream os=null;
try
{
is=new FileInputStream(f1.getAbsolutePath()+"\\123.txt");
os=new FileOutputStream("D:\\Java项目相关代码\\123.txt");
byte[] buffer = new byte[1024];
int i = 0;
while ((i = is.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
java.io.FileNotFoundException: E:\Java项目相关代码 \123.txt (系统找不到指定的路
径。)但如果把 f1.getAbsolutePath()+"\\123.txt"
改成"E:\\Java项目相关代码\\123.txt"
就能顺利完成复制。
如果要用到getAbsolutePath来表示路径的,应该怎么改呢?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteCopyFile
{
public static void main(String[] args)
{
File f1 = new File( "E:\\Java项目相关代码 ");
File f2 = new File( "D:\\Java项目相关代码 ");
FileInputStream is=null;
FileOutputStream os=null;
try
{
is=new FileInputStream(f1.getAbsolutePath()+"\\123.txt");
os=new FileOutputStream("D:\\Java项目相关代码\\123.txt");
byte[] buffer = new byte[1024];
int i = 0;
while ((i = is.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
java.io.FileNotFoundException: E:\Java项目相关代码 \123.txt (系统找不到指定的路
径。)但如果把 f1.getAbsolutePath()+"\\123.txt"
改成"E:\\Java项目相关代码\\123.txt"
就能顺利完成复制。
如果要用到getAbsolutePath来表示路径的,应该怎么改呢?
知道了
这个结果是
"E:\Java项目相关代码\123.txt"
java中需要\\
但如果用getAbsolutePath应该怎么改呢?
path = path.replaceAll("\\", "\\\\");
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected in
ternal error near index 1
\
^
可能上面我猜的原因错了,
我换成
"E:\Java项目相关代码\123.txt"
会显示 非法的转义字符
而用f1.getAbsolutePath()+"\\123.txt"
显示的是找不到指定的路径
f1.getAbsolutePath()+“\\"+"123.txt"
系统会无法找到路径而"E:\\Java项目相关代码\\123.txt"
就可以呢?
new File(xxx, "123.txt").getAbsolutePath();
is=new FileInputStream("E:\\Java项目相关代码\\123.txt");
String str="E:\\Java项目相关代码\\123.txt";
System.out.println(str);
System.out.println(f1.getAbsolutePath()+"\\123.txt");
System.out.println(str==f1.getAbsolutePath());发现了
输出
E:\Java项目相关代码\123.txt
E:\Java项目相关代码 \123.txt //用getAbsolutePath() 后面
false编写一个去掉字符串空格的方法就能成功复制文件了。
也是 E:\Java项目相关代码 \123.txt
而不是E:\Java项目相关代码\123.txt
getAbsolutePath()得到的路径怎么有个空格?
而且参数是File,String 的时候
在String表示的文件名前面有个空格?