Accessing a file in a runnable JAR [duplicate] - java

This question already has answers here:
Java resource as File
(6 answers)
Closed 9 years ago.
What I am attempting to do is store a text file (that won't change) inside the JAR of the program so that it can be read. The purpose of the text file is that it will be read in by one of my classes and the contents of the text file will be added to an JEditorPane. The file will basically be a tutorial and when the user clicks on the option to read the tutorial, the file contents will be read and displayed in a new window that pops up.
I have the GUI portion of it down, but as far as storing the file in the JAR so it can be accessed, I am at a lost. I've read that using an InputStream will work, but after trying a few things I haven't gotten it to work yet.
I also store images in the JAR to be used as icons for the GUI windows. This is accomplished with:
private Image icon = new ImageIcon(getClass()
.getResource("resources/cricket.jpg")).getImage();
But, this doesn't work when trying to get a file:
private File file = new File(getClass.getResource("resources/howto.txt"));
Here is my Class as it is now:
public class HowToScreen extends JFrame{
/**
*
*/
private static final long serialVersionUID = -3760362453964229085L;
private JEditorPane howtoScreen = new JEditorPane("text/html", "");
private Image icon = new ImageIcon(getClass().getResource("resources/cricket.jpg")).getImage();
private BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/howto.txt")));
public HowToScreen(){
setSize(400,300);
setLocation(500,200);
setTitle("Daily Text Tutorial");
setIconImage(icon);
howtoScreen.setEditable(false);
howtoScreen.setText(importFileStream());
add(howtoScreen);
setVisible(true);
}
public String importFile(){
String text = "";
File file = new File("howto.txt");
Scanner in = null;
try {
in = new Scanner(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(in.hasNext()){
text += in.nextLine();
}
in.close();
return text;
}
public String importFileStream(){
String text = "";
Scanner in = new Scanner(txtReader);
while(in.hasNext()){
text += in.nextLine();
}
in.close();
return text;
}
}
Ignore the importFile method as that is being removed in favor of storing the tutorial file inside the JAR, making the program wholly self contained as I am limited to how much space the program can use.
EDIT:
After trying all of the suggestions below, I checked to see if my JAR is packaging the text file in it and it is not. When opening the JAR with 7zip, in my resources folder the picture I use for icons is there, but not the text file.

You cannot use File inside a JAR file. You need to use InputStream to read the text data.
BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/mytextfile.txt")));
// ... Use the buffered reader to read the text file.

Try the next (with the full path package):
InputStream inputStream = ClassLoader.getSystemClassLoader().
getSystemResourceAsStream("com/company/resources/howto.txt");
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader in = new BufferedReader(streamReader);
for (String line; (line = in.readLine()) != null;) {
// do something with the line
}

You code will not compile. Class.getResource() returns a URL, and File has no constructor with a URL as an argument.
You can just use .getResourceAsStream() instead, it returns an InputStream directly, you just have to read the contents of the file from that stream.
Note: both of these methods return null if the resource is not found: don't forget to check for that...

the contents of the text file will be added to an JEditorPane.
See DocumentVewer & especially JEditorPane.setPage(URL).
Since the help is an embedded-resource it will be necessary to gain an URL using getResource(String) as detailed in the info. page.
.. tried this: URL url = this.getClass().getResource("resources/howto.txt");
Change:
URL url = this.getClass().getResource("resources/howto.txt");
To:
URL url = this.getClass().getResource("/resources/howto.txt"); // note leading '/'

Related

JCombobox not working on jar

I have one application that fills a JComboBox with the content of a text file (.db precisely). Everything works fine on IDE, however when creating a .jar nothing show on the JComboBox.
The code is as following:
private void fill(String type) throws FileNotFoundException {
BufferedReader input = null; // used to read file content
try {
input = new BufferedReader(new FileReader("pack"+ File.separator +type+".db")); // loading the file based on previous box (see image).
} catch (FileNotFoundException ex) {
Logger.getLogger(Calc.class.getName()).log(Level.SEVERE, null, ex);
}
try {
String line = null;
while (( line = input.readLine()) != null){
type_list.addItem(line); // adding to my JComboBox
}
input.close();`
As stated everything works fine on netbeans IDE and I get the following
IDE
However on .jar I get the following:
JAR
I tried reading the file from inputStream, with no success. I'm compiling the .db files with my application, but it's not mandatory for me (I can have .jar+ db files separately).
Thank you!!!
--------------------EDIT-------------------------------
I solved the problem using
InputStream is = this.getClass().getResourceAsStream("file.db");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Thank you so much for the help :)
By the time of deployment, those resources will likely become an embedded-resource. That being the case, the resource must be accessed by URL instead of File. See the info page for the tag, for a way to form an URL.

FileNotFoundException java cannot basic find file while it's there

I'm trying to read a basic txt file that contains prices in euros. My program is supposed to loop through these prices and then create a new file with the other prices. Now, the problem is that java says it cannot find the first file.
It is in the exact same package like this:
Java already fails at the following code:
FileReader fr = new FileReader("prices_usd.txt");
Whole code :
import java.io.*;
public class DollarToEur {
public static void main(String[] arg) throws IOException, FileNotFoundException {
FileReader fr = new FileReader("prices_usd.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("prices_eur");
PrintWriter pw = new PrintWriter(fw);
String regel = br.readLine();
while(regel != null) {
String[] values = regel.split(" : ");
String beschrijving = values[0];
String prijsString = values[1];
double prijs = Double.parseDouble(prijsString);
double newPrijs = prijs * 0.913;
pw.println(beschrijving + " : " + newPrijs);
regel = br.readLine();
}
pw.close();
br.close();
}
}
Your file looks to be named "prices_usd" and your code is looking for "prices_usd.txt"
There are a couple of things you need to do:
Put the file directly under the project folder in Eclipse. When your execute your code in Eclipse, the project folder is considered to be the working directory. So you need to put the file there so that Java can find it.
Rename the file correctly with the .txt extn. From your screen print it looks like the file does not have an extension or may be it's just not visible.
Hope this helps!
It is bad practice to put resource files (like prices_usd.txt) in a package. Please put it under the resources/ directory. If you put it directly in the resources/ directory, you can access the file like this:
new FileReader(new File(this.getClass().getClassLoader().getResource("prices_usd.txt").getFile()));
But if you really have a good reason to put it in the package, you can access it like this:
new FileReader("src/main/java/week5/practicum13/prices_usd.txt");
But this will not work when you export your project (for example: as a jar).
EDIT 0: Also of course, your file's name needs to be "prices_usd.txt" and not just "prices_usd".
EDIT 1: The first (recommended) solution does return a string on .getFile() which can not directly be passed to the new File(...) constructor when the application is built / not run in the IDE. Spring has a solution to it though: org.springframework.core.io.ClassPathResource.
Simply use this code with Spring:
new FileReader(new ClassPathResource("prices_usd.txt").getFile());

What folder should I store text files?

I have my classes in /src/com.example.myapp/ and I have a text mytext.txt there too.
However, when I reference static File f = new File("mytext.txt")); it does not find it, even though the file is in the same directory as the class.
What do I need to do? What directory is it actually looking in?
Assets is read-only. I need somewhere where I can read and update the text file.
Use an assets folder.
Here is an example...
Loading array from a text file in assets folder (Android)
You create the assets folder in your root project folder then place your file in it. Once it's there, you access this way:
getAssets().open("file.txt");
the getAssets method is part of your Activity / Context. Context carriers a lot of the information about your app.
If you are not in an Activity, you can pass the Context to your class and use this:
context.getAssets().open("file.txt");
If you want the file with EDIT mode, you can use Internal/External Storage
Then you can read it as:
String filePath = context.getFilesDir().getAbsolutePath(); //returns current directory.
File file = new File(filePath, fileName);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
}
return text.toString(); //the output text from file.
You can even write to this file :
String filename = "myfile";
String string = "ur data";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Hope it will help you ツ
Use the assets directory:
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

Broken Text : reading larger size text in android

i have a question about Broken text when android app is reading large size text file.
I am trying to build the app to read large size text file(about 10mb)
when I am reading a file and using System.println to check the contents of text file
However, when I display message but print statement
it displays broken text such as..
��T��h��e�� ��P��r��o��j��e��c��t�� ��G��u
when I was reading small size of rtf was find, but i used text file then i made problems
I used code like ..
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
File gone = new File(path);
FileInputStream inputStream = new FileInputStream(gone);
// FileInputStream inputStream = openFileInput(gone);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,UTF8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader, BUFFER_SIZE);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
System.out.println(ret);
}
I was thinking about that it can be problem of encoding. there fore i added utf8 option.
However, it still doesn't work ..
Does anyone know solution of broken text ?
UPDATE:
I think, I solved problem.
I create new text file from window text editor and then i copy and paste content.
Now , it is reading file correctly
It may be wrong encoding for the given file, may be the file does not contain text, may be console does not support the characters.
Besides the code is too long, here's a one line solution
String s = new String(Files.readAllBytes(Paths.get(file)), "UTF-8");
The file may contain images or unsupported format, in that case it'll display like that.

File Delete and Rename in Java

I have the following Java code which will search in an xml for a specific tag and then will add some text to it and save that file. I couldnt find a way to rename the emporary file to the original file. Please suggest.
import java.io.*;
class ModifyXML {
public void readMyFile(String inputLine) throws Exception
{
String record = "";
File outFile = new File("tempFile.tmp");
FileInputStream fis = new FileInputStream("InfectiousDisease.xml");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
while ( (record=br.readLine()) != null )
{
if(record.endsWith("<add-info>"))
{
out.println(" "+"<add-info>");
out.println(" "+inputLine);
}
else
{
out.println(record);
}
}
out.flush();
out.close();
br.close();
//Also we need to delete the original file
//outFile.renameTo(InfectiousDisease.xml);//Not working
}
public static void main (String[] args) {
try
{
ModifyXML f = new ModifyXML();
f.readMyFile("This is infectious disease data");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Thanks
First delete the original file and then rename the new file:
File inputFile = new File("InfectiousDisease.xml");
File outFile = new File("tempFile.tmp");
if(inputFile.delete()){
outFile.renameTo(inputFile);
}
A good method to rename files is.
File file = new File("path-here");
file.renameTo(new File("new path here"));
In your code there are several issues.
First your description mentions renameing the original file and adding some text to it. Your code doesn't do that, it opens two files, one for reading and one for writing (with the additional text). That is the right way to do things, as adding text in-place is not really feasible using the techniques you are using.
The second issue is that you are opening a temporary file. Temporary files remove themselves upon closing, so all the work you did adding your text disappears as soon as you close the file.
The third issue is that you are modifying XML files as plain text. This sometimes works as XML files are a subset of plain text files, but there is no indication that you attempted to ensure that the output file was an XML file. Perhaps you know more about your input files than is mentioned, but if you want this to work correctly for 100% of the input cases, you probably want to create a SAX writer that writes out all a SAX reader reads, with the additional information in the correct tag location.
You can use
outFile.renameTo(new File(newFileName));
You have to ensure these files are not open at the time.

Categories

Resources