Error reading file in a jar - java

I'm trying to read a file in java, when I run the program through the IDE it works fine but when it tries to open it when I execute the jar it says the file does not exist. Here is the code where it fails.
public class Main {
public static void main(String[] args) {
try {
App app = new App("files/" + "jsonFile.json", printWriter);
app.runApp();
} catch (Exception e) {
logger.error("error", e);
}
}
}
public class App {
public void runApp(){
File fileDescription = new File("./" + pathDescription);
StringBuilder allDescription = new StringBuilder();
try {
FileReader fr = new FileReader(fileDescription);
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null) {
allDescription.append(line);
}
JSONDescription = allDescription.toString();
fr.close();
br.close();
} catch (IOException e) {
logger.error("Error reading file",e);
}
}
}
I know the file exists inside the jar because I looked manually into the jar using jarzilla. Any idea of what it could be happening.

You can lookup a file inside a jar using something like this:
InputStream stream = ClassInsideTheJar.class.getResourceAsStream("/files/jsonFile.json");
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
Where "ClassInsideTheJar" is any class in the jar.

To access files within the JAR, you could use something like
BufferedReader reader = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("files/jsonFile.json")));
This assumes that there is a folder called files in the root of your jar, and inside that you have the jsonFile.json file.

When you run the program inside an IDE, the compiled code exists outside the jar, in the file system. The IDE compile the code, and then run the program, without building the JAR file. So, your program found the file, because that file still exists in the file system.
To open a file inside a JAR, you need to use another API: loading the file as a resource.
load file within a jar

Related

how to read files from Internal Storage

Iam new to android programming
this code is giving FilenotFound Exception
and going through catch block
where should i save my .txt file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCOde=findViewById(R.id.code);
String filename="bully rap.txt";
try {
readCode(filename);
} catch (Exception e) {
myCOde.setText("file not found");
}
}
private void readCode(String filename) throws Exception{
File filesDir=MainActivity.this.getFilesDir();
File myFile=new File(filesDir,filename);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String st;
StringBuilder code= new StringBuilder("hello");
while ((st = br.readLine()) != null){
code.append(st);
myCOde.setText(code);
}
Using below code is not gonna help you to achieve what you want.
File filesDir = MainActivity.this.getFilesDir();
Above code usually returns the path where /data/data/{your package name}/files. If you want to access an external file directory, as in you case like Download folder you should use something like below.
String filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Furthermore if you are going to write to an external file directory, you may need to add neccessary permissions in the manifest.xml

Unable to write to the file, Created in java using File class

Class MakeDirectory contains the constructor, and in the constructor I created a directory and inside that directory I created a file. But I am unable to write anything to the newly created file, even though the file and directory have been generated successfully. Can anyone help me figure out why I am not able to write to the file Anything.txt?
public class MakeDirectory {
MakeDirectory() throws IOException{
// Creates Directory
File mydir= new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir","Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
PrintWriter pr= new PrintWriter(myfile);
pr.write("This file is created through java");
}
public static void main(String args[]) throws IOException {
new MakeDirectory();
}
}
If you want to use PrintWriter you need to know that it is not automatically flushing. After you write you need to flush. Also, don't forget to close your PrintWriter!
PrintWriter pw = new PrintWriter(myFile);
pw.write("text");
pw.flush();
pw.close();
An approach available in Java 7 employs the try-with-resources construct. Using this feature, the code would look like the following:
try (PrintWriter pw = new PrintWriter("myFile")) {
pw.write("text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
With BufferedWriter you can just write the strings, arrays or characters data directly to the file:
void makeDirectory() throws IOException {
// Creates Directory
File mydir = new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir", "Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
BufferedWriter bw = new BufferedWriter(new FileWriter(myfile.getAbsoluteFile()));
String str = "This file is created through java";
bw.write(str);
bw.close();
}

How can I load an xml resource file from within an executible Jar file and save it to the folder the jar is located in?

I have a custom java server. It uses an external xml config file.
I have some command line options to help the user, the usual stuff for showing a help file, setting ports, etc...
I've recently added a command to generate a default config file for the server. It's an xml file. After researching my options, packing a default xml file in the jar seemed to be the way to go, but I'm obviously missing something.
So far my code looks like this:
public class ResourceLoader {
private File outFile = null;
private Reader fileReader = null;
private Writer fileWriter = null;
private InputStream is = null;
private char[] buffer = null;
public ResourceLoader() {
outFile = new File("default-server.xml");
}
public void generateDefaultServerXml() {
is = ResourceLoader.class.getResourceAsStream("/default-server.xml");
if (is == null) {
System.out.println("Configuraiton File generation failed. The InputStream is null.");
} else {
fileReader = new InputStreamReader(is);
}
buffer = new char[4096];
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
fileWriter = new OutputStreamWriter(fos);
while (fileReader.read(buffer) != -1) {
fileWriter.write(buffer, 0, buffer.length);
fileWriter.flush();
buffer = new char[4096];
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fileReader.close();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The code above works perfectly fine when I run it in eclipse, but intitially, after I export the jar file the server could not locate the default-server.xml file when I run the command from the terminal.
The file itself is located in a package called main.resources along with some other config files and the above class.
I have since moved the ResourceLoader.class to another package. After doing that the server seems to find the xml file in the main.resources package (InputStream is not null) but the resulting generated default-server.xml file is empty.
Again, this all works perfectly well when I run it in eclipse, it's only after I export the project and try issue the command from the terminal that the process fails. What am I doing wrong?
The above class is instantiated, and the generateDefaultServerXml() is called, from the main method of the server.
EDIT: My path for writing default-server.xml was slightly wrong. Now that I've adjusted it the code works exactly as expected when I run it in Eclipse. The resource is read in the correct way, and written to the file in the correct location. But it still doesn't work when I try the same thing from the jar file.
You current line ResourceLoader.class.getResourceAsStream("/default-server.xml") means that you are trying to load a resource named default-server.xml from the root of your classpath, or put simpler, from the root of your jar file. This means that xml file should NOT be in any package inside the jar file.
When you assemble your jar file and then run jar tf my.jar on it, do you see your default-server.xml file? Does it reside in some package or in the root of the jar file?
The problem here is since you are packaging the application as a jar. The procedure to call an external resource is quite different.
You need to have a folder structure as
root
--your jar
--your xml file
Your code shallwork if the application is using an default-server.xml file inside the jar.
Otherwise, Replace below line in your code if you want to use an external default xml file.
is = new FileInputStream("./default-server.xml");
If the output file you want at root location the use below code
public ResourceLoader() {
outFile = new File("./default-server.xml");
}
Alternate code as per discussion
public class ResourceLoader {
public void generateDefaultServerXml() {
try {
String defaultxmltext =readFileToString("/default-server.xml");
writeFileFromInputString(defaultxmltext);
} catch (IOException e) {
//exception
}
}
public static void writeFileFromInputString(String everything) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("./default-server.xml"))) {
everything = everything.replaceAll("\n", System.getProperty("line.separator"));
writer.write(everything);
}
}
public static String readFileToString(String path) throws IOException {
String everything = null;
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
}
return everything;
}
}
Hope this helps
consider your file located on src/main/resources try this
getClass().getClassLoader().getResource(fileName)
well as far as i can see your main problem is that you are passing the wrong path, since you mentioned the xml is under main.resources you will need to add this to the path when trying to load the file, here is a sample piece of code that should work for you
Scanner sc = null;
PrintWriter writer = null;
try {
sc = new Scanner(getClass().getResourceAsStream("main/resources/server.xml"));
writer = new PrintWriter("./default_server.xml", "UTF-8");
while(sc.hasNextLine()) {
writer.println(sc.nextLine());
}
} catch (Exception e) {
} finally {
if(sc != null) {
sc.close();
}
if(writer != null){
writer.close();
}
}

Deleting files opened within a JavaFX application

I'm currently working on a JavaFX application that uses a save file to load information about the previous session. I am having problems closing my BufferedReader and BufferedWriters. Files are not being unlocked until the JavaFX application is terminated. I have traced through the code and to ensure that there are no BufferedReaders and BufferedWriters left un-closed. If I try to modify the files after JavaFX is closed, they will be renamed and deleted correctly. Here's an example of one of my methods for reading and writing to files.
This is a school assignment and external libraries are not allowed.
public static boolean addNewAccount(User user, String fileName)
{
try
{
File output = new File("temp.csv");
File input = new File(fileName);
if (output.exists())
{
output.delete();
output.createNewFile();
}
BufferedWriter outputStream = new BufferedWriter(new FileWriter(output.getName()));
BufferedReader inputStream = new BufferedReader(new FileReader(input.getName()));
...
Read and write stuff here.
...
inputStream.close();
inputStream = null;
outputStream.close();
outputStream = null;
System.gc();
input.delete();
if (!output.renameTo(input))
{
HistoryLog.getInstance().log("Something is preventing a file from being closed.");
return false;
}
}
catch (IOException e)
{
e.printStackTrace();
return false;
}
return true;
}

Where is the folder for assets?

Simple Question I know - but my android app simply can´t find my CSV file. I´ve placed the file here:
and access it with this code:
public void getFragenfromCSV(){
AssetManager a = getAssets();
BufferedReader reader = null;
try {
InputStream is = a.open("fragenbronze.csv");
reader = new BufferedReader(new InputStreamReader(s));
} catch (IOException e) {
System.out.println("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
e.printStackTrace();
}
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
System.out.println(RowData[0]);
}
}
catch (IOException ex) {
// handle exception
}
}
On running the app I always get the IOException from the catch part.
you have to place it in
src/main/assets
never put something you want to keep in build/ as this get's removed with clean
Project Structure with assets folder
You are going inside build but actually you have to go inside src/main/assets.

Categories

Resources