Get Uri from file in either assets or res/raw - java

I have tried to get this working and I have looked at many different resources online (as you can see from all of the comments I have made). I want to access a .pdf file that is either located in assets or res; It does not matter to which one so the easiest way will do.
I have the method below that will get the actual file and will call another method(under the first method below) with the Uri in the parameters.
Thank you very much for your help and I will be standing by to answer questions or add more content.
private void showDocument(File file)
{
//////////// ORIGINAL ////////////////////
//showDocument(Uri.fromFile(file));
//////////////////////////////////////////
// try 1
//File file = new File("file:///android_asset/RELATIVEPATH");
// try 2
//Resources resources = this.getResources();
// try 4
String PLACEHOLDER= "file:///android_asset/example.pdf";
File f = new File(PLACEHOLDER);
//File f = new File("android.resource://res/raw/slides1/example.pdf");
//getResources().openRawResource(R.raw.example);
// try 3
//Resources resources = this.getResources();
//showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));
showDocument(Uri.fromFile(f));
}
protected abstract void showDocument(Uri uri);

from link & Get URI of .mp3 file stored in res/raw folder in android
sing the resource id, the format is:
"android.resource://[package]/[res id]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);
or, using the resource subdirectory (type) and resource name (filename without extension), the format is:
"android.resource://[package]/[res type]/[res name]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");

If you do not know the ID of your resource, but just the name, you can use the getIdentifier(...) method of the Android Resouces object. You can retrieve the latter using the getResources() of your application context.
If, for example, your resource is stored in the /res/raw folder:
String rawFileName = "example" // your file name (e.g. "example.pdf") without the extension
//Retrieve the resource ID:
int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
if ( resID == 0 ) { // the resource file does NOT exist!!
//Debug:
Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");
return;
}
//Read the resource:
InputStream inputStream = context.getResources().openRawResource(resID);

Very Helpful post.
Here's an alternative: Work with a FileDescriptor instead of the Uri, where possible.
Example: (In my case its a raw audio file)
FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();
this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);

Related

save file with different name in spring boot

I am uploading one file that is kind of multipart. I want this file to save with different name.
tried with renameTo method but did not work.
tried moveto but did not work
below is my code
here graphic is multipart file
String picName = graphic.getOriginalFilename();EN_LENGTH) + "." + graphic.getContentType();
Path dirLocation = Paths.get(dirPath);
String newName = CommonUtil.getToken(Constants.STANDRAD_TOKEN_LENGTH) + "." + graphic.getContentType();
try {
InputStream is = graphic.getInputStream();
Files.copy(is, dirLocation.resolve(picName), StandardCopyOption.REPLACE_EXISTING);
boolean a = new File(dirLocation+picName).renameTo(new File(dirLocation+newName));
for security reasons I want it to save with different name.
Solved the issue by correcting the filename. The file name which I was generating randomly was not correct. it had some slash etc.

Grails 3 Loading Static Files

I have a few PDF files in the assets folder of a Grails 3 application. I want to load them when the user clicks some button. i.e User clicks button "Get first book", and a grails controller looks for all files in the assets folder until it finds a match, and then returns the correct one.
Currently, I am loading the files by directly accessing the path. i.e. I am using an explicit aboslute path. According to this post, this is one of the advisable approaches. However, I want to load a file in grails by asking my application to get all assets in the asset folder, instead of using any paths.
My question then is, is it possible to get all files from the assets folder in a simple manner like we can get properties in the yml file (grailsApplication.config.someProperty)
Found the solution here: Grails : getting assets local storage path inside the controller
The following sample:
def assetResourceLocator
assetResourceLocator.findAssetForURI('file.jpg')?.getInputStream()?.bytes
worked fine for me.
this code makes something similar for me (however, my files are located outside of my project directory). Its a controller method, that receives the file name (id) and the filetype (filetype) and looks in a predefined directory. I think you just have to adapt your "serverLocation" and "contentLocation".
To get a list of the files, which you can pass to the view:
List listOfNewsletters = []
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File f = new File(serverLocation);
if (f.exists()) {
f.eachFile() { File file ->
listOfNewsletters.push([
path: file.path,
filename: file.name,
filetype: "pdf"
])
}
}
To deliver the file:
def openNewsletter() {
if (params.id != null && params.filetype != null) {
String pdf = (String) params.id + "." + (String) params.filetype;
String contentLocation = grailsApplication.config.managedNewsletter.contentLocation;
File rootDirectory = new File(servletContext.getRealPath("/"));
File webappsDirectory = rootDirectory.getParentFile();
String serverLocation = webappsDirectory.getAbsolutePath();
serverLocation = serverLocation + contentLocation + "/";
File pdfFile =new File(serverLocation + pdf);
response.contentType = 'application/pdf' // or whatever content type your resources are
response.outputStream << pdfFile.getBytes()
response.outputStream.flush()
}
}

How to get Specific Image from Document And Media Folder in jsp

I have Successfully created folder and uploaded file in Document and Media Library.
I am storing File Name in DB and based on that file name I want to fetch that specific file from Document Library. I am new to Liferay.
I am fetching all Files saved in Document & Media Library using this Code Snippet. But is there any way to directly fetch File using File Name.
Here is my Code Snippet
public void getAllDLFileLink(ThemeDisplay themeDisplay,String folderName){
try {
Folder folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(themeDisplay.getScopeGroupId(), folder.getFolderId());
for (DLFileEntry file : dlFileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
System.out.println("DL Link=>"+url);
}
} catch (Exception e) {
e.printStackTrace();
}
}
As your code snippet already finds the URL for a DLFileEntry, I'm assuming that you want to get hold of the binary content. Check DLFileEntry.getContentStream().
If this assumption is wrong and you want to embed the image in the HTML output of your portlet, use the URL within an <img src="URL-HERE"/> tag
You can use DLFileEntryLocalServiceUtil.getFileEntry(long groupId, long folderId, java.lang.String title) to get file using file name / title, as following:
String fileName = "abc.jpg";
Folder folder = DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(),
DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, folderName);
DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.getFileEntry(
themeDisplay.getScopeGroupId(), folder.getFolderId(), fileName);
However, title is stored with extension, therefore, you will require to pass complete name of image / file.

How can I change uploaded files directory in play 2.0.1?

I tried to specify attachments.path property in my application.conf file, but this had no effects.
In the documentation of play 2.0.1 I didn't find anything explaining how to change uploaded files directory.
Am I missing something?
Although there is no such variable in application.conf you can easily add it and use in your method. Call it as you wish ie:
new line in application.conf:
myUploadPath = "/home/your-account/some/custom/upload/folder/"
according to the documentation sample:
public static Result upload() {
MultipartFormData body = request().body().asMultipartFormData();
MultipartFormData.FilePart picture = body.getFile("picture");
if (picture != null) {
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
// added lines
String myUploadPath = Play.application().configuration().getString("myUploadPath");
file.renameTo(new File(myUploadPath, fileName));
return ok("file saved as " + myUploadPath + fileName);
} else {
flash("error", "Missing file");
return redirect(routes.Application.uploadform());
}
}
Using this approach you can or even should perform filename clash check before renaming, to prevent random overwriting.

url = new java.net.URL()

url = new java.net.URL(s) doesn't work for me.
I have a string C:\apache-tomcat-6.0.29\webapps\XEPServlet\files\m1.fo and need to make a link and give it to my formatter for output, but malformed url recieved. It seems that it doesn't make my string to url.
I want also mention, that file m1.fo file is in files folder, in my webapp\product\, and I gave the full path to string like: getServletContext().getRealPath("files/m1.fo"). What I am doing wrong? How can I recieve the url link?
It is possible to get an URL from a file path with the java.io.File API :
String path = "C:\\apache-tomcat-6.0.29\\webapps\\XEPServlet\\files\\m1.fo";
File f = new File(path);
URL url = f.toURI().toURL();
Try: file:///C:/apache-tomcat-6.0.29/webapps/XEPServlet/files/m1.fo
It isn't preferable to write file:/// . Indeed it works on windows system,but in unix - there were problems.
Instead of using
myReq.put("xml", new String []{"file:" + System.getProperty("file.separator") +
getServletContext().getRealPath(DESTINATION_DIR_PATH) +
System.getProperty("file.separator") + xmlfile});
you can write
myReq.put("xml", new String [] {getUploadedFileURL (xmlfile)} );
, where
public String getUploadedFileURL(String filename) {
java.io.File filePath = new java.io.File(new
java.io.File(getServletContext().getRealPath(DESTINATION_DIR_PATH)),
filename);
return filePath.toURI().toURL().toString();
A file system path is not a URL. A URL is going to need a protocol prefix for one. To reference file system use "file:" in front of your path.

Categories

Resources