Java system resource as file

Java resource as File

ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don’t believe there’s any way of «listing» the contents of an element of the classpath.

In some cases this may be simply impossible — for instance, a ClassLoader could generate data on the fly, based on what resource name it’s asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you’ll see there isn’t anything to do what you want.

If you know you’ve actually got a jar file, you could load that with ZipInputStream to find out what’s available. It will mean you’ll have different code for directories and jar files though.

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.

Solution 2

I had the same problem and was able to use the following:

// Load the directory as a resource URL dir_url = ClassLoader.getSystemResource(dir_path); // Turn the resource into a File object File dir = new File(dir_url.toURI()); // List the directory String files = dir.list() 

Solution 3

Here is a bit of code from one of my applications. Let me know if it suits your needs. You can use this if you know the file you want to use.

URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png"); File imageFile = new File(defaultImage.toURI()); 

Solution 4

A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) < try < InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath); if (in == null) < return null; >File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp"); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) < //copy stream byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) < out.write(buffer, 0, bytesRead); >> return tempFile; > catch (IOException e) < e.printStackTrace(); return null; >> 

Solution 5

ClassLoader.getResourceAsStream ("some/pkg/resource.properties"); 

Источник

Читайте также:  Delete all element in list python

Java resource as File

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Question: How do I write a list to a file? doesn’t insert newline characters, so I need to do: Solution 1: Use a loop: For Python

Java resource as File

Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?

My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I’m looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively

Edit: Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?

I had the same problem and was able to use the following:

// Load the directory as a resource URL dir_url = ClassLoader.getSystemResource(dir_path); // Turn the resource into a File object File dir = new File(dir_url.toURI()); // List the directory String files = dir.list() 

ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don’t believe there’s any way of «listing» the contents of an element of the classpath.

In some cases this may be simply impossible — for instance, a ClassLoader could generate data on the fly, based on what resource name it’s asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you’ll see there isn’t anything to do what you want.

If you know you’ve actually got a jar file, you could load that with ZipInputStream to find out what’s available. It will mean you’ll have different code for directories and jar files though.

One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.

Here is a bit of code from one of my applications. Let me know if it suits your needs. You can use this if you know the file you want to use.

URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png"); File imageFile = new File(defaultImage.toURI()); 

A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):

public static File getResourceAsFile(String resourcePath) < try < InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath); if (in == null) < return null; >File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp"); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) < //copy stream byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) < out.write(buffer, 0, bytesRead); >> return tempFile; > catch (IOException e) < e.printStackTrace(); return null; >> 

How to send file contents as body entity using cURL, If you want to send the file with newlines intact, use —data-binary in place of —data. If you want to be real fancy you can do: cat file.txt | curl —data «@-» ` (< url.txt )` @- tells curl to read from stdin. You could also just use the redirect (< x.txt ) to put in whatever you want. If you're using bash.

Writing a list to a file with Python, with newlines

How do I write a list to a file? writelines() doesn’t insert newline characters, so I need to do:

f.writelines([f"\n" for line in lines]) 
with open('your_file.txt', 'w') as f: for line in lines: f.write(f"\n") 
with open('your_file.txt', 'w') as f: for line in lines: f.write("%s\n" % line) 

For Python 2, one may also use:

with open('your_file.txt', 'w') as f: for line in lines: print >> f, line 

If you’re keen on a single function call, at least remove the square brackets [] , so that the strings to be printed get made one at a time (a genexp rather than a listcomp) — no reason to take up all the memory required to materialize the whole list of strings.

What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements?

If you are just trying to serialize a list to disk for later use by the same python app, you should be pickleing the list.

import pickle with open('outfile', 'wb') as fp: pickle.dump(itemlist, fp) 
with open ('outfile', 'rb') as fp: itemlist = pickle.load(fp) 
with open("outfile", "w") as outfile: outfile.write("\n".join(itemlist)) 

To ensure that all items in the item list are strings, use a generator expression:

with open("outfile", "w") as outfile: outfile.write("\n".join(str(item) for item in itemlist)) 

Remember that itemlist takes up memory, so take care about the memory consumption.

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler: for item in the_list: file_handler.write("<>\n".format(item)) 

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, «<>\n».format(item) can be replaced with an f-string: f»\n» .

How to save a list as a CSV, Nope, pandas deal well with csv. Just use its method read_csv. if you realy need ‘,’ at the end of line, run: df[‘colummn’] = df[‘colummn’].map(lambda x: x+»,») However csv format does not suppose file to have ‘,’ at the end of line, only in between columns. Adding ‘,’ after words would mean that there is a second column (what …

How to send file contents as body entity using cURL

I am using cURL command line utility to send HTTP POST to a web service. I want to include a file’s contents as the body entity of the POST. I have tried using -d as well as other variants with type info like —data —data-urlencode etc. the file is always attached. I need it as the body entity.

I believe you’re looking for the @filename syntax, e.g.:

curl --data "@/path/to/filename" http://. 
curl --data-binary "@/path/to/filename" http://. 

curl will strip all newlines from the file. If you want to send the file with newlines intact, use —data-binary in place of —data

I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:

curl -X POST -H --silent --data-urlencode "payload=" https://hooks.slack.com/services/XXX 

In my case, @ caused some sort of encoding problem, I still prefer my old way:

curl -d "$(cat /path/to/file)" https://example.com 

curl https://upload.box.com/api/2.0/files/3300/content -H «Authorization: Bearer $access_token» -F file=@»C:\Crystal Reports\Crystal Reports\mysales.pdf»

Examples to Save Excel File using VBA Save As Function, Follow the below steps to convert this file into a PDF Using VBA Save As function: Step 1: Define a new sub-procedure to store a macro. Step 2: Now, use the following code to save this file as a PDF file. Step 3: Run this code and you’ll see a pdf file generated under This PC > Documents.

Источник

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