When I copy a picture into the folder with resources and try to insert it, then getClass().getClassLoader().getResource(nameFile); is null , and the file is copied successfully. If you restart the program and select the same picture then everything will work. What could be the problem?

  public void actionPerformed(ActionEvent e) { /* * Π’Ρ‹Π±ΠΎΡ€ ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ */ FileDialog dialog = new FileDialog((Frame)null, "Π’ΠΈΠ±Π΅Ρ€Ρ–Ρ‚ΡŒ ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΡƒ"); dialog.setMode(FileDialog.LOAD); dialog.setVisible(true); File file = new File(dialog.getDirectory() + dialog.getFile()); /* * ΠšΠΎΠΏΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ Π² ΠΏΠ°ΠΏΠΊΡƒ с рисурсами */ try { String fileName = new File(new File("").getAbsoluteFile() + "\\src\\main\\resources\\" + dialog.getFile()).toString(); if (!(new File(fileName)).exists()) { copyFileUsingJava7Files(file, new File(new File(".").getAbsoluteFile() + "\\src\\main\\resources\\" + dialog.getFile())); } } catch (Exception e1) { e1.printStackTrace(); } /* * Вставка ΠΈΠ·ΠΎΠ±Ρ€Π°ΠΆΠ΅Π½ΠΈΠ΅ Π² ΠΊΠΎΠ½Π΅Ρ† тСкста JTextPane */ URL imgUrl= getClass().getClassLoader().getResource(dialog.getFile()); HTMLDocument doc=(HTMLDocument) textPane.getStyledDocument(); try { System.out.println(imgUrl); doc.insertAfterEnd(doc.getCharacterElement(doc.getLength()),"<img src=\"" + imgUrl + "\">"); } catch (BadLocationException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } 

    1 answer 1

    The problem was in the URL, without a clue why. In general, made a new URL and everything worked URL imgUrl = file.toURL();