英文:
How to get the a file from drag n dropped paths
问题
所以这可能是一个非常新手的问题,但我创建了一个JTextField,用户可以将文件拖放进去,以避免在Swing树中点击半小时。这给了我一个类似这样的字符串:
file:///media/raphael/Coding/Test/Test%20rscs/Test%20Exercise.asf
(我知道文件格式很不寻常,这是从我的代码生成的)。这个路径由于开头的%20和file://,无法正常工作。所以我写了一个函数得到了这个路径:
/media/raphael/Coding/Test/Test rscs/Test Exercise.asf
,但是当我将它传递给BufferedReader br = new BufferedReader(new FileReader(this.path));
时,仍然不起作用,抛出一个文件未找到的异常。奇怪的是,当我在IntelliJ中捕获异常时,路径显示为指向文件的链接,所以路径实际上是有效的?我需要怎么做才能让Java识别这个路径呢?
英文:
So really noobie question i suppose but i made a JTextField where the user can drag and drop files in to avoid clicking through the swing tree for half an hour. This gives me a String like
file:///media/raphael/Coding/Test/Test%20rscs/Test%20Exercise.asf
(i know the file format is unnusual, its generated from my own code) This path doesn't work because of the %20 and the file:// at the beginning. So i made a function giving me this: /media/raphael/Coding/Test/Test rscs/Test Exercise.asf
But this still doesnt work when plugged into BufferedReader br = new BufferedReader(new FileReader(this.path));
, giving me a File not found exception. The strange thing is that when i get the exception in intellij, the path is displayed as a link which leads to the file, so the path is actually valid? What do i have to do in order to make java recognize the path?
答案1
得分: 0
问题是,拖放操作会在放置的任何内容末尾添加一个额外的空格。当然,在错误消息或System.out.println();
中看不到此空格。因此,解决方案是,如果字符串的最后一个字符是
,则将其删除。
英文:
The problem was, that drag 'n' drop adds an aditional space at the end of anything dropped. This space of course is not visible in error messages or System.out.println();
. Therefore the solution is to remove the last char of the String if it is ' '.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论