getAbsolutePath() 
返回此抽象路径名的绝对路径名字符串。
抽象路径怎么理解 是不是相对路径
getCanonicalPath() 
返回此抽象路径名的规范路径名字符串。
发现这两个都一样 输出来的路径形式都是一样的下面是我写的测试程序import javax.swing.*;
import java.awt.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.BorderLayout;public class JFrameDemo01
{
static BufferedImage image;
public static void main(String args[]){
JFrame f = new JFrame("the first swing");
Dimension d = new Dimension();
d.setSize(600,600);
f.setSize(d);
Point p = new Point(200,150);
f.setLocation(p);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel j = new JPanel();
j.setLayout(new BorderLayout());
JButton jb = new JButton();
j.add(jb,BorderLayout.CENTER);
f.add(j);


JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "JPG & GIF Images", "jpg", "gif");
 chooser.setFileFilter(filter);
 int returnVal = chooser.showOpenDialog(f);
 if(returnVal == JFileChooser.APPROVE_OPTION) {
 System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
 }
File file = chooser.getCurrentDirectory();
System.out.println("1. "+file.getAbsolutePath());
System.out.println(file.isAbsolute());
try
{
System.out.println("2. "+file.getCanonicalPath());
System.out.println("3. "+file.getCanonicalPath());
}
catch (Exception e)
{
}

try {
image = ImageIO.read(chooser.getSelectedFile()); 
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon ii = new ImageIcon(image);
jb.setIcon(ii);
System.out.println(jb.getIcon());

}请高手解释下 顺便解释一下相对路径和绝对路径 都好久了 还没懂这两个路径

解决方案 »

  1.   

    File file = chooser.getCurrentDirectory();
    这样的话得到的file不是选择的文件,图片也显示不到Button上
      

  2.   

    未选择文件的时候抛异常刚才学习了下,你可以试一试:
    好像是如果file用的是绝对路径的话 两者没区别
    如果用的是相对路径的时候两者输出的就不一样
    File file=new File("../a.txt");
    System.out.println(file.getCanonicalPath());
    System.out.println(file.getAbsolutePath());
    输出结果:C:\Documents and Settings\Administrator\Workspaces\MyEclipse 8.x\a.txt
    C:\Documents and Settings\Administrator\Workspaces\MyEclipse 8.x\SETest\..\a.txtgetCanonicalPath会计算出文件的绝对路径 而absolute则不会
      

  3.   

    1. getAbsolutePath()  
    返回此抽象路径名的绝对路径名字符串。
    这个函数返回的路径里面可以有., ..,来代表当前目录或者父级目录,如
    File file = new File("/home/../data.txt");
    file.getAbsolutePath() 返回的是 /home/../data.txt,这个路径实际上是/data.txt2. getCanonicalPath()  
    返回此抽象路径名的规范路径名字符串。
    这个函数不会像上一个函数一样返回的路径里可以包含.,..
    File file = new File("/home/../data.txt");
    file.getCanonicalPath() 返回的是 /data.txt