I am trying to write a bitmap to any of the usual internal folders like 'Pictures, Documents, Download' etc. Below is the file creation I am doing
String root = Environment.getRootDirectory().toString();
File myDir = new File(root + File.separator + Environment.DIRECTORY_PICTURES);
String Filename = "pic.png";
File fl = new File(myDir + File.separator + Filename);
FileOutputStream out = new FileOutputStream(fl);
At the last line, it throws an exception which says 'No such File/Directory'.
If I check fl.canWrite(), it says false!, i.e. fl is not writable.
I even tried to give 'Unrestricted Access' in my testing mobile for this App.
What could be the problem?
What kind of additional things I need to do?
Edit: When I toast, myDir is shown as /system/Pictures. When I go to File Manager in phone, under my 'Phone storage', 'Pictures' folder is there. That's a usual folder in Android right ?
you should use
\\...
File myDir = new File(Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
\\...
then do a check to confirm directory exist and then proceed to write your file.
Related
I'm trying to create a folder on my device and the result isn't as expected.
I do have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml.
My code:
public void saveOnDevice(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/hello");
boolean x = true;
if (!myDir.exists()) {
x = myDir.mkdirs();
}
if(x) {
System.out.println("Folder created " + root);
}
else{
System.out.println("Folder not created" + root);
}
}
Result:
Folder not created /storage/emulated/0
Expected:
Folder created /storage/emulated/0
I tried this on my Samsung Galaxy S8. I don't have a SD-Card inserted. I don't have the path /storage/emulated/0 on my device. Why isn't it working and how can I fix this problem?
You do have that folder /storage/emulated/0 on your device. You probably just can't see it due to the layer of abstraction when using Samsungs file browser.
You can verify that by using a more advanced file browser such as FX File Explorer (https://play.google.com/store/apps/details?id=nextapp.fx) and start looking up that path from "System /".
That root string won't help you.
Instead you want to do something like this:
// create folder "myDir" in internal storage as sub directory of /storage/emulated/0
File myDir = new File(Environment.getExternalStorageDirectory(), "myDir");
// create file
File myFile = new File(myDir, "song.mp3");
// get file stream
FileOutputStream fileStream = new FileOutputStream(myFile);
Then you can simply write your songs content to fileStream.
It's a bit confusing that Environment.getExternalStorageDirectory() actually gives you the internal storage location, but it is external to your apps directory which is something like Android/your.apps.packagename/.
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.
I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}
I have a program which includes the following line of code:
//String s = fileName;
File location = new File(s);
and then I have
//String contents = whatIWantToPrint;
OutputStream print = new FileOutputStream(location);
print.write(contents.getBytes());
print.close();
telling the program to print the string contents to the file s. However the file appears within the folder that the program is in rather than the directory in which the program is in. For example if the program is on the persons desktop I want it to make the file on their desktop.
I used the following line in terminal to make the program a jar file (mac):
jar -cvmf manifest.txt Generate.jar *.class
Someone told me to do this:
String dir = System.getProperty("home.dir"+"/Desktop");
String filePath = dir + File.separator + ss + ".txt";
File location = new File(filePath);
But I'm not sure if that's what will make the program make the file in the desktop and it also throws a security exception so it doesn't work anyways
You should do:
String s= System.getProperty("user.home");
and append path separator and file name
String filePath = s + File.separator + "desktop" + File.separator + "myFile.txt";
You could try this
String DEFAULT_USER_DIR = System
.getProperty("user.home"+"/Desktop");
File location = new File(DEFAULT_USER_DIR);
user.dir returns User's current working directory
See the javadoc here.
How can I get file size in Java if I have a relative path to a file such as:
String s = "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with two diferent strings:
String[] separatedPath = s.split("/");
List<String> wordList = Arrays.asList(separatedPath);
String ret = "/" + wordList.get(1) + "/" + wordList.get(2) + "/" + wordList.get(3)+ "/" + wordList.get(4);
s = ret;
In this case s="/documents/19/21704/file2.pdf";
In second case s="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc"
I tried with:
File file1 = new File(s);
long filesize = file1.length();
and with:
String filePath = new File(s).toURI().getPath();
File file2 = new File(filePath);
long filesize2 = file1.length();
and also with (if the problem is in not providing full path):
String absolutePath = FileUtil.getAbsolutePath(file1);
File file3 = new File(absolutePath);
long filesize3 = file3.length();
byte[] bytes1=FileUtil.getBytes(file1);
byte[] bytes2=FileUtil.getBytes(file2);
byte[] bytes3=FileUtil.getBytes(file3);
I am always getting in debug that filesizes in all cases are 0.
Maybe is worth noticing that the three attributes of file1 and file2 and file3 are always:
filePath: which is always null;
path: "/documents/19/21704/liferay-portlet-development.pdf"
prefixLength: 1
Since I am also using Liferay I also tried their utility.
long compId = article.getCompanyId();
long contentLength = DLStoreUtil.getFileSize(compId, CompanyConstants.SYSTEM, s);
I also should notice that in my .xhtml view I can access the file with:
<a target="_blank"
href="/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc">
file2.pdf
</a>
Pdf opens in a new window. So it is stored on my server.
What am I doing wrong here? That I cant get the file size from bean?
Any answer would be greatly appreciated.
What am I doing wrong here?
In Java, you can use the File.length() method to get the file size in bytes.
File file =new File("c:\\java_xml_logo.jpg");
if(file.exists()){
double bytes = file.length();
}
System.out.println("bytes : " + bytes);
The problem is that your "relative" path is expressed as an absolute path (begining with "/", which is read as FS root).
A relative file path should look like:
documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
./documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc
Or, you could get your application root folder File and compose the absolute path:
File rootFolder =new File("path to your app root folder");
File myfile=new File(rootFolder, "/documents/19/21704/file2.pdf/0929c695-d023-49d7-a8ff-65ccea46bebc");