Why am I getting a NoSuchFileException when running readAllBytes on this file - java

I am trying to make a simple android app that uses OpenAPLR
http://doc.openalpr.com/cloud_api.html
So I copied the code under the Java section on how to make a REST api request and put it all into onClick method of a button and took a picture of a license plate and saved it as license_plate.jpg in the location
app/res/drawable/license_plate.jpg
But whenever I run the application I always get an error pointing to these lines
Path path = Paths.get("drawable/license_plate.jpg");
byte[] data = Files.readAllBytes(path);
java.nio.file.NoSuchFileException: drawable/license_plate.jpg
Where should I be saving this image so I can use it during the application?
And where should I be saving images used for future applications when I am not just using a single picture I have already preloaded?

You give wrong path. You can only save a picture in your device and
then give image folder path for example :
Path path = Paths.get("/storage/projects/alpr/samples/testing/car1.jpg");
byte[] data = Files.readAllBytes(path);

Related

Why my loop is executing after another statements even if it is placed before that statement in Android Studio [duplicate]

Is there a way in Firebase Storage to generate a download url pointing to nothing, in order to upload a file to that url later? something like that (in Kotlin):
fun generateItemPhotoUrl(id: String) =
storageRef.child("$Id/${generateUniqueName()}.${COMPRESS_FORMAT.name}").downloadUrl
This code returns a failed task...
I want this so my upload process can look like so:
// Case: old photo is null but new one is not - upload new photo to a new uri
generateItemPhotoUrl(itemId).continueWithTask { generateTask ->
if (generateTask.isSuccessful) {
val destUrl = generateTask.result.toString()
// Uploading may take time, so first update document to hold a uri, so consecutive
// calls will result in updating instead of uploading a new file
updateItemPhoto(itemId, destUrl).continueWithTask { updateTask ->
if (updateTask.isSuccessful)
uploadFileToDest(destUrl, newImage).continueWithTask { uploadTask ->
if (!uploadTask.isSuccessful) updateItemPhoto(itemId, null)
}
}
}
}
As explained in code, I need this to prevent the case of updating the item's photo twice in a row too fast for the first one to finish it's upload. I end up with 2 files - one of them is not referenced from anywhere. If I could do something like this, the second upload will go to my "update" case (instead of the "new photo" case presented here) - where the file will be switched correctly.
Is there a way in Firebase Storage to generate a download URL pointing to nothing, in order to upload a file to that URL later?
No, this is not possible. You cannot generate a Storage URL in advance and upload the file sometime later. You get the download URL only when the file is successfully uploaded on the Firebase servers. This is because the URL that comes from the UploadTask contains a token that is generated on the server, and it's apart of the URL. To get the entire download URL of an uploaded file, please see my answer from the following post:
How to get the download url from Firebase Storage?
The process of uploading the file is asynchronous, meaning that any code that needs that URL, needs to be inside the" onSuccess()" method, or be called from there. So there is no need to upload the file twice.

JavaFX: ImageView cannot load image that was created by the program itself. Error: java.lang.IllegalArgumentException:

I am attempting to create a program in which the user selects an image from a different folder on their computer and JavaFX copies that image into the project directory for future use. A new folder is created that will store the newly created image file. This is essentially the code for selecting and copying the image into the project directory:
Stage window = (Stage) ap.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Select Image File");
File selectedFile = fileChooser.showOpenDialog(window);
//Creates a new directory for the new calendar that the user wants to create
File file = new File("src/DefaultUser/" + nameField.getText() + "/");
file.mkdir();
//Creates a new file name with logo as the name, but keeping the extension the same
int index = selectedFile.getName().lastIndexOf(".");
String ext = selectedFile.getName().substring(index);
//Stored in newFileName
String newFileName = "logo" + ext;
File newFile = new File(file.getPath() + "/" + newFileName);
//Copies the selected file into the project src folder, with newFileName as the new file name
Files.copy(selectedFile.toPath(), newFile.toPath());
Then the program moves onto a different scene and thus a different controller actually loads the image into an ImageView. I know that the path for the Image works properly but for whatever reason the program cannot find the image file to load it into the ImageView.
Here is essentially the code used for that:
image.setImage(new Image("DefaultUser/" + imagePath));
Don't worry about what imagePath is in this case because I am absolutely positive it paths to the correct location for the newly created image file. This is because if I close the JavaFX program and rerun it, the image loads properly.
At first, I thought it was because it took time for the image to be copied into the project directory but I checked that the file actually existed within the code and it did so this is apparently not the case. I tried using Thread.sleep() to delay the program a bit so that the code would potentially have more time to copy the file but it still threw the same error: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
The strangest part about this is that the program works perfectly fine, it's just that I have to restart the JavaFX program for it to be able to detect the image file, even though I know it exists. Is there something weird about JavaFX and creating new files and accessing them within the same program? I am truly lost. Thank you so much in advance for any help and I'm sorry if this doesn't give enough information because I don't want to have to explain the whole project.
Just like haraldK and James_D said in the comments putting stuff in the src folder is generally a bad idea. I solved the issue by moving the folder out into the project directory instead.

Groovy: Save gform input type file to the assets pipeline (or similar)

(Sorry if this is simple; this is my first post)
Is the groovy/grails asset pipeline modifiable at runtime?
Problem: I am creating an application where users create the objects. The objects are stored as text files so that only the necessary objects are built at runtime. Currently, the text file includes a string which represents the filename of the image. The plan was to have these images stored in assets/images/ as this works best for later displaying the object. However, now I am running into issues with saving files to assets/images/ at run time, and I can't even figure out if this is possible. *Displaying images already works in the way I require if I drag and drop the images into the desired folder, however I need a way for the controller to put the image there instead. The relevant section of controller code:
def folder = new File("languageDevelopment/grails-app/assets/images/")
//println folder
def f = request.getFile('keyImage');
if (f.empty)
{
flash.message = 'file cannot be empty'
render(view: 'create')
return
}
f.transferTo(folder)
The error I'm receiving is a fileNotFoundException
"/var/folders/9c/0brqct9j6pj4j85wnc5zljvc0000gn/T/languageDevelopment/grails-app/assets/images (No such file or directory)"
on f.transferTo(folder)
What is the section it is adding to the beginning of my "folder" object?
Thanks in advance. If you need more information or have a suggestion to a different route please let me know!
new File("languageDevelopment/grails-app/assets/images/")
This folder is present only in your sources
After deployment it will looks like "/PATH-TO-TOMCAT/webapps/ROOT/assets/" if you use tomcat.
Also asset/images, asset/font etc. will be merged to assets folder.
If you'd like to store temporary files you can create some directory under src/resources folder.
For example "src/resources/images"
And you can get access to this folder from classloader:
this.class.classLoader.getResource('images/someImage.png').path

Changed Image file is not getting displayed using struts2

I am tring to upload a file using struts2.File uploading is successful.I tried out many hints from stack overflow,but still failed to find a solution for this.
Nw when i try to change the image,the new image appears only after clearing the cache.It does not change spontaneously.The struts2 framwork makes use of tiles and
the images are getting displayed on header and leftContainer.
The file is named after the memberId logged in..(which is stored in session)
I made use of fileUpload code from:
http://www.tutorialspoint.com/struts_2/struts_file_uploads.htm
destPath = org.apache.struts2.ServletActionContext.getServletContext().getRealPath("/");
destPath = destPath + "images";
//where images are stored in images folder of webapps..
When i try uploading a new image,this image will be renamed by the memberId of the loggedin member(stored in session).
What my exact problem is that, new file is getting successfully uploaded to the images path.It is also renamed correctly.But this new image appears only when i either refresh the page or clear the cache.Why is this so??
How can refreshing be avoided?
Please help..........

how to read image from project folder in java?

I am developing web method for webservice in java. In this web method I have to read image from my images folder which resides in my webservice project folder. I am using the code as follows.
#WebMethod(operationName = "getAddvertisementImage")
public Vector getAddvertisementImage()
{
Image image = null;
Vector imageList = new Vector();
try
{
File file = new File("E:/SBTS/SBTSWebservice/web/adv_btm.jpg");
image = ImageIO.read(file);
imageList.add(image);
}
catch (IOException e)
{
e.printStackTrace();
}
return imageList;
}
I am unable to read image from images folder.I am getting error image file "input file can't read" at image = ImageIO.read(file); how to resolve this issue ? Is there any mistake in my code or is there any other way to read image ? if there is any mistake in my code then can you proide me the code or link through which i can resolve the above issue.
Is the E:\ drive mapped on your web server? The Java compiler has no idea that you might access files outside of its scope and how it could tell your web server to map a network drive or a local hard disk which is attached to your development computer.
The solution is to put the image file into the same directory as the Java source file and then use
InputStream in = getClass().getResourceAsStream("adv_btm.jpg");
Check that your IDE (or whatever you use to build your application) does copy the image file in the same directory where it creates the .class file. Then it should work.

Categories

Resources