我试图通过拖放到JTextField来打开文件,但我总是得到错误。
继承我的代码
public void drop(DropTargetDropEvent dtde) {
String str4=null;
try {
JTextArea comp = null;
if(Switchtab==2)
comp=textarea1;
if(Switchtab==3)
comp=textarea2;
if(Switchtab==4)
comp=textarea3;
if(Switchtab==1)
comp=textarea4;
// Ok, get the dropped object and try to figure out what it is
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
for (int i = 0; i < flavors.length; i++) {
System.out.println("Possible flavor: "
+ flavors[i].getMimeType());
// Check for file lists specifically
if (flavors[i].isFlavorJavaFileListType()) {
// Great! Accept copy drops...
dtde.acceptDrop(DnDConstants.ACTION_COPY);
// comp.setText("Successful file list drop.\n\n");
// And add the list of file names to our text area
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
//wcomp.append(list.get(j) + "\n");
str4=list.get(j)+"\n";
}
// Replace '\' with '/'
file_pth = str4.replaceAll("\\\\","/" );
System.out.println(str4.replaceAll("\\\\","/" ));
//Open the file
try {
File f = new File(file_pth);
FileInputStream fobj = new FileInputStream(f);
int len = (int) f.length();
str4 = "";
for (int j = 0; j < len; j++) {
char str5 = (char) fobj.read();
str4 = str4 + str5;
}
comp.setText(str4);
setTitle(str4);
} catch (Exception e) {
System.out.println("Caught::" + e);
}
// If we made it this far, everything worked.
dtde.dropComplete(true);
return;
}
}
// Hmm, the user must not have dropped a file list
System.out.println("Drop failed: " + dtde);
dtde.rejectDrop();
} catch (Exception e) {
e.printStackTrace();
dtde.rejectDrop();
}
}
我甚至尝试使用双反斜杠和正斜杠替换反斜杠但仍然会出现此错误
Possible flavor: application/x-java-file-list; class=java.util.List
C:/kevin_java/file io/DemoIO.java
Caught::java.io.FileNotFoundException: C:\kevin_java\file io\DemoIO.java
(The filename, directory name, or volume label syntax is incorrect)
输出不显示替换的字符串。 它显示前一个带有单反斜杠的字符串。
答案 0 :(得分:0)
修改强>
来自isFlavorJavaFileListType
的{{3}},
如果指定的DataFlavor表示文件对象列表,则返回true。
THEREFOR,
FileInputStream fobj = new FileInputStream(list.get(list.length()-1));
答案 1 :(得分:0)
最后我得到了答案。 简单的解决方案
java.util.List list = (java.util.List) tr
.getTransferData(flavors[i]);
for (int j = 0; j < list.size(); j++) {
str4=list.get(j).toString();
}
File f = new File(str4);
FileInputStream fobj = new FileInputStream(f);
...
...
..