Java – drag and drop txt files into textarea
•
Java
Here I have a text area called sourcetx, where I drag and drop the file, and then use BufferedReader to read the contents of the file From the following code, I can see that I have set up the file and I am using absolutepath to read the content
So when I drag and drop some Txt file, it will work, it will read the content and put it in the text area, but when I also drag and drop some folders, for example, it will also read some content and put it in the text area
So I want to make this drag and drop read-only Txt file? How can I get that?
This is the code of the method:
public void dragDrop(){ sourceTx.setOnDragOver(new EventHandler <DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); if(db.hasFiles()){ event.acceptTransferModes(TransferMode.ANY); for(File file:db.getFiles()){ String absolutePath = file.getAbsolutePath(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath))); String line = null; String text = ""; String nl = System.getProperty("line.separator","\n"); while((line = br.readLine()) != null) text += line + nl; sourceTx.setText( text.trim() ); } catch (Exception e) { Message@R_113_2419@.show(Message@R_113_2419@Type.ERROR,I18n.localize("File Error"),I18n.localize("Error while reading content from selected file")); } finally{ if(br != null) try { br.close(); } catch (Exception e) {} } } }else{ event.setDropCompleted(false); } event.consume(); } }); }
Solution
Hello, try to read your file recursively
... for (File file : db.getFiles()) { sourceTx.setText(handleFile(file)); } ... private String handleFile(File file) { String ret = ""; if (file.isDirectory()) { for (File f : file.listFiles()) { ret.concat(handleFile(f)); } } else { /*this is your filereader*/ String absolutePath = file.getAbsolutePath(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream(absolutePath))); String line = null; String text = ""; String nl = System.getProperty("line.separator","\n"); while ((line = br.readLine()) != null) text += line + nl; ret.concat(text.trim()); } catch (Exception e) { Message@R_113_2419@.show(Message@R_113_2419@Type.ERROR,I18n.localize("Error while reading content from selected file")); } finally { if (br != null) try { br.close(); } catch (Exception e) { } } } return ret; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码