File imageFile = new File(chooser.getSelectedFile().getName()); //chooser是JFileChooer的一个实例
String filePath = imageFile.getAbsolutePath(); //filePath = filePath.replace('\\', '/');
System.out.println("the file is "+filePath); //打印的并不是文件的目录,而是eclipse
//workplace下的目录
//比如我选择E:\1.jpg,实际得到的文件路径是%eclipseHome%\workplace\myTest\1.jpg
//这个是什么原因呢,希望贵人指教
File imageFile = new File(chooser.getSelectedFile().getName()); 改为:File imageFile = new File(chooser.getSelectedFile().getAbsolutePath());
这里改为
File imageFile = new File(chooser.getSelectedFile().getAbsolutePath());
应该就可以了。
你的这句代码:chooser.getSelectedFile()返回的就是一个File的实例了,不需要再getName()了,只要想楼上那样,返回它的绝对路径就可以了...
File imageFile = new File(chooser.getSelectedFile()); //chooser是JFileChooer的一个实例
String filePath = imageFile.getAbsolutePath();
String filePath = imageFile.getAbsolutePath();
调用这个方法之后得到的是什么?你仔细想想:chooser.getSelectedFile().getName());
应该是得到了 E:\1.jpg 这个文件的文件名字,也就是一个字符串 “1.jpg ”,
这样你的第一行语句 File imageFile = new File(chooser.getSelectedFile().getName());
就可以等价为:File imageFile = new File(“1.jpg”);
这就相当于在当前的工作目录下新建了一个文件名为 1.jpg的文件了,你原来从FileChoose里面的到的文件
也就丢失了,在这里用到的只是文件的一个名字,一个字符串而已。所以,按照你说的情况的话,我估计你需要的做法应该是 1 楼说的那样File imageFile = new File(chooser.getSelectedFile().getName()); 改为: File imageFile = new File(chooser.getSelectedFile().getAbsolutePath());