先链接一下文件路径的分隔符使用,一般用左斜线,Windows的右斜线需要转义
/**
* \/ 名称分隔符 separator
* @param args
*/
public static void main(String[] args) {
String path = "F:\\workspace\\IO_study01\\13442345515565744.jpg";
System.out.println(File.separatorChar);
//建议:
//1:/
path = "F:/workspace/IO_study01/13442345515565744.jpg";
System.out.println(path);
//2:常量拼接
path = "F:"+File.separator+"workspace"+File.separator+"IO_stydy01"+File.separator+"13442345515565744.jpg";
System.out.println(path);
}
根据File 的构造器构建对象:jdk手册:
/**
* 构建File对象
* @param args
*/
public static void main(String[] args) {
String path = "F:/workspace/IO_study01/13442345515565744.jpg";
//1,构建File对象 :路径名
File src = new File(path);
System.out.println(src.length());
//2,构建File对象: 父子路径
src = new File("F:/workspace/IO_study01","13442345515565744.jpg");
src = new File("F:/workspace","IO_study01/13442345515565744.jpg");
System.out.println(src.length());
//3,构建File对象:父对象,子名称
src = new File(new File("F:/workspace/IO_study01"),"13442345515565744.jpg");
System.out.println(src.length());
}
区分相对路径和绝对路径:
/**
* 构建File对象
* 相对路径和绝对路径
* 1:存在盘符:绝对路径
* 2:不存在盘符,相对路径
* @param args
*/
public static void main(String[] args) {
String path = "F:/workspace/IO_study01/13442345515565744.jpg";
//绝对路径
File src = new File(path);
System.out.println(src.getAbsolutePath());//获取绝对路径
//相对路径
src = new File("13442345515565744.jpg");
System.out.println(src.getAbsolutePath());//获取绝对路径
//构建一个不存在的路径
src = new File("aa/fdf.jpg");
System.out.println(src.getAbsolutePath());
}