Failed to load file java lang nullpointerexception

NullPointerException when reading a properties file in Java

It looks like ClassLoader.getResourceAsStream(String name) returns null , which then causes Properties.load to throw NullPointerException .

Here’s an excerpt from documentation:

  • the resource could not be found, or
  • the invoker doesn’t have adequate privileges to get the resource.

See also

@udy: can you edit the question and add more information about what IDE you’re using, where you currently put the properties file, and how you’re running the project etc?

Bugfixing is easier if you write more lines, like:

Properties properties = new Properties(); Thread currentThread = Thread.currentThread(); ClassLoader contextClassLoader = currentThread.getContextClassLoader(); InputStream propertiesStream = contextClassLoader.getResourceAsStream("resource.properties"); if (propertiesStream != null) < properties.load(propertiesStream); // TODO close the stream >else < // Properties file not found! >

Oh, thanks, thanks, this works for me finally! I tried many of quite similar codes (for run within jar) before and I was already completely desperate.

I had the same problem and was quite confused as I used it previously in a Sturts application. But the problem was that I didn’t understand the type of ClassLoader that Struts returns is different than what Spring returns. And the way i figured it out was i printed out the object that was returned on to the system console like this:

System.out.println(Thread.currentThread().getContextClassLoader()); 
[
WebappClassLoader
context: /MyProject
delegate: false
repositories:
/WEB-INF/classes/
———-> Parent Classloader:
org.apache.catalina.loader.StandardClassLoader@1004901
]
Читайте также:  Button action method php

It gave me the detail of the object, and in that I found its type to be of WebAppClassLoader which will start looking for files in the WEB-INF/classes/ folder after a build is done. So I went into the that folder and looked for where my file is located so I gave the path accordingly.

In my case it was located in /WEB-INF/classes/META-INF/spring/filename.extension

InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/spring/filename.extension"); 

Источник

Ошибка java.lang.nullpointerexception, как исправить?

Ряд пользователей (да и разработчиков) программных продуктов на языке Java могут столкнуться с ошибкой java.lang.nullpointerexception (сокращённо NPE), при возникновении которой запущенная программа прекращает свою работу. Обычно это связано с некорректно написанным телом какой-либо программы на Java, требуя от разработчиков соответствующих действий для исправления проблемы. В этом материале я расскажу, что это за ошибка, какова её специфика, а также поясню, как исправить ошибку java.lang.nullpointerexception.

Что это за ошибка java.lang.nullpointerexception

Появление данной ошибки знаменует собой ситуацию, при которой разработчик программы пытается вызвать метод по нулевой ссылке на объект. В тексте сообщения об ошибке система обычно указывает stack trace и номер строки, в которой возникла ошибка, по которым проблему будет легко отследить.

Номер строки с ошибкой

Что в отношении обычных пользователей, то появление ошибки java.lang.nullpointerexception у вас на ПК сигнализирует, что у вас что-то не так с функционалом пакетом Java на вашем компьютере, или что программа (или онлайн-приложение), работающие на Java, функционируют не совсем корректно. Если у вас возникает проблема, при которой Java апплет не загружен, рекомендую изучить материал по ссылке.

Скриншот ошибки Java

Как исправить ошибку java.lang.nullpointerexception

Как избавиться от ошибки java.lang.nullpointerexception? Способы борьбы с проблемой можно разделить на две основные группы – для пользователей и для разработчиков.

Для пользователей

Если вы встретились с данной ошибкой во время запуска (или работы) какой-либо программы (особенно это касается minecraft), то рекомендую выполнить следующее:

Картинка Minecraft

  1. Переустановите пакет Java на своём компьютере. Скачать пакет можно, к примеру, вот отсюда;
  2. Переустановите саму проблемную программу (или удалите проблемное обновление, если ошибка начала появляться после такового);
  3. Напишите письмо в техническую поддержку программы (или ресурса) с подробным описанием проблемы и ждите ответа, возможно, разработчики скоро пофиксят баг.
  4. Также, в случае проблем в работе игры Майнкрафт, некоторым пользователям помогло создание новой учётной записи с административными правами, и запуск игры от её имени.

Для разработчиков

Разработчикам стоит обратить внимание на следующее:

Картинка об ошибке java.lang.nullpointerexception

  1. Вызывайте методы equals(), а также equalsIgnoreCase() в известной строке литерала, и избегайте вызова данных методов у неизвестного объекта;
  2. Вместо toString() используйте valueOf() в ситуации, когда результат равнозначен;
  3. Применяйте null-безопасные библиотеки и методы;
  4. Старайтесь избегать возвращения null из метода, лучше возвращайте пустую коллекцию;
  5. Применяйте аннотации @Nullable и @NotNull;
  6. Не нужно лишней автоупаковки и автораспаковки в создаваемом вами коде, что приводит к созданию ненужных временных объектов;
  7. Регламентируйте границы на уровне СУБД;
  8. Правильно объявляйте соглашения о кодировании и выполняйте их.

Заключение

При устранении ошибки java.lang.nullpointerexception важно понимать, что данная проблема имеет программную основу, и мало коррелирует с ошибками ПК у обычного пользователя. В большинстве случаев необходимо непосредственное вмешательство разработчиков, способное исправить возникшую проблему и наладить работу программного продукта (или ресурса, на котором запущен сам продукт). В случае же, если ошибка возникла у обычного пользователя (довольно часто касается сбоев в работе игры Minecraft), рекомендуется установить свежий пакет Java на ПК, а также переустановить проблемную программу.

Источник

Why am I getting a NullPointerException when trying to read a file?

Sounds like the resource probably doesn’t exist with that name.

Are you aware that Class.getResourceAsStream() finds a resource relative to that class’s package, whereas ClassLoader.getResourceAsStream() doesn’t? You can use a leading forward slash in Class.getResourceAsStream() to mimic this, so

Foo.class.getResourceAsStream("/bar.png") 
Foo.class.getClassLoader().getResourceAsStream("bar.png") 

Is this actually a file (i.e. a specific file on the normal file system) that you’re trying to load? If so, using FileInputStream would be a better bet. Use Class.getResourceAsStream() if it’s a resource bundled in a jar file or in the classpath in some other way; use FileInputStream if it’s an arbitrary file which could be anywhere in the file system.

EDIT: Another thing to be careful of, which has caused me problems before now — if this has worked on your dev box which happens to be Windows, and is now failing on a production server which happens to be Unix, check the case of the filename. The fact that different file systems handle case-sensitivity differently can be a pain.

Are you checking to see if the file exists before you pass it to readFilesInBytes() ? Note that Class.getResourceAsStream() returns null if the file cannot be found. You probably want to do:

private static byte[] readFilesInBytes(String file) throws IOException < File testFile = new File(file); if (!testFile.exists()) < throw new FileNotFoundException("File " + file + " does not exist"); >return IOUtils.toByteArray(TestConversion.class.getResourceAsStream(file)); > 
private static byte[] readFilesInBytes(String file) throws IOException < InputStream stream = TestConversion.class.getResourceAsStream(file); if (stream == null) < throw new FileNotFoundException("readFilesInBytes: File " + file + " does not exist"); >return IOUtils.toByteArray(stream); > 

This class reads a TXT file in the classpath and uses TextConversion to convert to PDF, then save the pdf in the file system.

package convert.pdf.txt; //Conversion to PDF from text using iText. import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import convert.pdf.ConversionToPDF; import convert.pdf.ConvertDocumentException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfWriter; public class TextConversion implements ConversionToPDF < public byte[] convertDocument(byte[] documents) throws ConvertDocumentException < try < return this.convertInternal(documents); >catch (DocumentException e) < throw new ConvertDocumentException(e); >catch (IOException e) < throw new ConvertDocumentException(e); >> private byte[] convertInternal(byte[] documents) throws DocumentException, IOException < Document document = new Document(); ByteArrayOutputStream pdfResultBytes = new ByteArrayOutputStream(); PdfWriter.getInstance(document, pdfResultBytes); document.open(); BufferedReader reader = new BufferedReader( new InputStreamReader( new ByteArrayInputStream(documents) ) ); String line = ""; while ((line = reader.readLine()) != null) < if ("".equals(line.trim())) < line = "\n"; //white line >Font fonteDefault = new Font(Font.COURIER, 10); Paragraph paragraph = new Paragraph(line, fonteDefault); document.add(paragraph); > reader.close(); document.close(); return pdfResultBytes.toByteArray(); > > 

And here the code to ConversionToPDF :

package convert.pdf; // Interface implemented by the conversion algorithms. public interface ConversionToPDF

I think the problem come from my file system (devbox on windows and server is Unix). I will try to modify my classpath.

Источник

Opening a file produces a java.lang.NullPointerException

I have a JFrame and on the frame I have JButton, what I want is when that file is clicked that the user can load a file using the java JFileChooser. I declare the FileChooser like this.

JButton btnLoad = new JButton("Load .txt"); btnLoad.addActionListener(new ActionListener() < public void actionPerformed(ActionEvent e) < int returnVal = fc.showOpenDialog(OpenFile.this); if (returnVal == JFileChooser.APPROVE_OPTION) < File file = fc.getSelectedFile(); //This is where a real application would open the file. System.out.println("Opening: " + file.getName() + "."); >else < System.out.println("Open command cancelled by user."); >> >); 

Exception in thread «AWT-EventQueue-0» java.lang.NullPointerException at maple.Netflix$2.actionPerformed(Netflix.java:73) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

int returnVal = fc.showOpenDialog(Netflix.this); 

Источник

java.lang.NullPointerException when reading from a text file [duplicate]

I am working on a coursework and I’m facing an exception when I try to load from a text file. I am trying to store the IDs and the Questions. The output should be :

258 MC Question Fill in the blank. A Node is generally defined inside another class, making it a(n) ____ class. Answer Private Inner Public Internal Selected 2 37 L5 Question How would you rate your programming skills? Answer Excellent Very good Good Not as good as they should be Poor Selected -1 
public static void main(String[] args) throws IOException < try (BufferedReader br = new BufferedReader(new FileReader("questions.txt"))) < Map < Integer, String >map = new HashMap < Integer, String >(); String line = br.readLine(); while (line != null) < String[] temp; temp = line.split(" "); int line = br.readLine(); line = br.readLine(); String question = line; line = br.readLine(); line = br.readLine(); while (line.trim() != ("Selected")) < line = br.readLine(); >line = br.readLine(); int selected = Integer.parseInt(line); line = br.readLine(); map.put(id, question); System.out.println(map); > > > 

Exception in thread «main» java.lang.NullPointerException at daos.test.main(test.java:47) C:\Users\droop\Desktop\DSA\New folder\dsaCW2Template\nbproject\build-impl.xml:1076: The following error occurred while executing this line: C:\Users\droop\Desktop\DSA\New folder\dsaCW2Template\nbproject\build-impl.xml:830: Java returned: 1 BUILD FAILED (total time: 0 seconds)

Источник

Оцените статью