PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 14, 2022

[FIXED] How to access a file while writing a Java external library

 November 14, 2022     external, jar, java     No comments   

Issue

I am writing a small Java Library (say project A) to be used externally (as a .JAR) in any other project (project B).

This is how project A looks like :

projectA
--src/main/java
  --packageOne
    ....
  --packageTwo
    --A.java // need to access the next few text files in this java file
    --ImportantTextOne.txt
    --ImportantTextTwo.txt
    --ImportantTextThree.txt

This is how project B will look like :

projectB
--src/main/java
  --B.java // I will use project A here.

I have tried importing the text files, but every time I use it as a .JAR externally in ProjectB, I always get some errors such as

java.nio.file.NoSuchFileException

I presume this is because of some class path issue.

So how do i correctly read my text files in ProjectA?

thanks in advance

Edit : I don't need the text files in projectB, they are just used once to pull text from in projectA. All I want is to correctly read those files in projectA, so I can import projectA in any project and not get errors.


Solution

So with the help of Hiran's response and digging around (also this) I figured it out.

File structure of the library you are writing :

projectA
--src/main/java
  --packageOne
    ....
  --packageTwo
    --A.java // need to access the next few text files in this java file
    --ImportantTextOne.txt
    --ImportantTextTwo.txt
    --ImportantTextThree.txt

Whenever reading a file, treat it as a resource. As when the class will be used as an external .JAR you will not be able to access files inside the .JAR. Instead follow this type of pattern :

A.java

URL url = this.getClass().getResource("ImportantTextOne.txt") // this assumes your text file is in the same location as A.java
InputStream in = url.openStream();
String text = new BufferedReader(
    new InputStreamReader(in, StandardCharsets.UTF_8))
    .lines()
    .collect(Collectors.joining("\n"));


Answered By - Aditya
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing