How to upload file using java ? - java

Hello i m trying to upload file using java file.. but i don't get it.. i get file size=0 i'm providing here my java code. tell me why i cant upload on particular folder. i want to store my file in particular folder. i am trying to get file size, file name but i got the null value where am i wrong please tell me.
public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException
{
//image upload logic
String folder_for_upload =(getPortletContext().getRealPath("/"));
//String folder=actionRequest.getParameter("uploadfolder");
realPath=getPortletContext().getRealPath("/");
logger.info("RealPath is" + realPath);
logger.info("Folder is :" + folder_for_upload);
try
{
logger.info("Admin is try to upload");
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
if (uploadRequest.getSize("fileName") == 0) {
SessionErrors.add(actionRequest, "error");
}
String sourceFileName = uploadRequest.getFileName("fileName");
File uploadedFile = uploadRequest.getFile("fileName");
System.out.println("Size of uploaded file: " + uploadRequest.getSize("fileName"));
logger.info("Uploded file name is: " + uploadRequest.getFileName("fileName"));
String destiFolder=("/home/ubuntu/liferay/liferay-portal-6.1.1-ce-ga2/tomcat-7.0.27/webapps/imageUpload-portlet/image");
String newsourcefilename = (uploadRequest.getFileName("fileName"));
File newFile = new File(destiFolder +"/"+ newsourcefilename);
logger.info("New file name: " + newFile.getName());
logger.info("New file path: " + newFile.getPath());
InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(uploadedFile);
FileOutputStream fos = new FileOutputStream(newFile);
byte[] bytes_ = FileUtil.getBytes(in);
int i = fis.read(bytes_);
while (i != -1) {
fos.write(bytes_, 0, i);
i = fis.read(bytes_);
}
fis.close();
fos.close();
Float size = (float) newFile.length();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);
logger.info("File created: " + newFile.getName());
SessionMessages.add(actionRequest, "success");
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (NullPointerException e)
{
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}
catch (IOException e1)
{
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}
}

You need to do this to upload small files < 1kb
File f2 = uploadRequest.getFile("fileupload", true);
They are stored in memory only. I have it in my catch statement incase I get a null pointer - or incase my original file (f1.length) == 0

I have executed your code.It is working as per expectation.There might be something wrong in your jsp page.I am not sure but might be your name attribute is not same as the one which you are using in processAction(assuming that you are using portlet).Parameter is case sensitive,so check it again.
You will find more on below link.It has good explanation in file upload.
http://www.codeyouneed.com/liferay-portlet-file-upload-tutorial/

I went through a file upload code, and when i implement that in my local system what i got is, portlet is saving the file i upload in tomcat/webbapp/abc_portlet_project location, what i dont understand is from where portlet found
String folder = getInitParameter("uploadFolder");
String realPath = getPortletContext().getRealPath("/");
System.out.println("RealPath" + realPath +"\\" + folder); try {
UploadPortletRequest uploadRequest =
PortalUtil.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));
if (uploadRequest.getSize("fileName")==0)
{SessionErrors.add(actionRequest, "error");}
String sourceFileName = uploadRequest.getFileName("fileName"); File
file = uploadRequest.getFile("fileName");
System.out.println("Nome file:" +
uploadRequest.getFileName("fileName")); File newFolder = null;
newFolder = new File(realPath +"\" + folder);
if(!newFolder.exists()){ newFolder.mkdir(); }
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("New file path: " + newfile.getPath());
InputStream in = new
BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
FileInputStream fis = new FileInputStream(file); FileOutputStream fos
= new FileOutputStream(newfile);

Related

Unable to save file to disk "No space left on device"

I've a java program that writes files to a directory on Linux VM. After writing 4.9 million files, it is failing with the following error:
java.io.FileNotFoundException: /home/user/test/6BA30639CA0A2772AA0217312B3E847E2399E9A25F50F9960D6A670F4F2533EF.blob.lock (No space left on device)
at java.io.RandomAccessFile.open0(Native Method)
at java.io.RandomAccessFile.open(RandomAccessFile.java:316)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:243)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:124)
at com.xyz.azure.AsyncADLSHashFileUploader.SaveToLocalStore(AsyncADLSHashFileUploader.java:231)
My logic is:
public String SaveToLocalStore(byte[] bytes, String subfolder) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bytes);
byte[] sha256 = md.digest();
String sha256str = bytesToHex(sha256);
Path tmpDir = Paths.get(LocalRootDirectory.toString(), subfolder);
Path tmpFile = Paths.get(tmpDir.toString(), sha256str + ".tmp");
Path localFile = Paths.get(LocalRootDirectory.toString(), subfolder, sha256str + ".blob");
String dstFile = getDestFileFromSrcFile(localFile.toString());
//noinspection ResultOfMethodCallIgnored
tmpDir.toFile().mkdirs();
//We can make a safe assumption that if the .blob file is present, that means that it has been fully written to
if (!Files.exists(localFile)) {
try (
RandomAccessFile randomAccessFile = new RandomAccessFile(localFile + ".lock", "rw");
FileChannel fc = randomAccessFile.getChannel();
FileLock fileLock = fc.tryLock()) {
//if other thread/process is already handling this file... no point of us doing anything
if (fileLock != null) {
//local file is already there, no need to write it again
try (FileOutputStream fos = new FileOutputStream(tmpFile.toString())) {
fos.write(bytes);
fos.flush();
fos.close();
Files.move(tmpFile, localFile, REPLACE_EXISTING);
if(statisticsEnabled) {
synchronized (StatsLock) {
StatsSavedHashes.add(localFile.toString());
}
}
} catch (Exception e) {
LOGGER.error("Failed to create local temp file: " + tmpFile + ": " + e, e);
//cleanup temp if it exists
Files.deleteIfExists(tmpFile);
throw e;
}
}
} catch (OverlappingFileLockException e) {
//other thread is handling it already, so just carry one as if(fileLock == null) was at play
return dstFile;
}
catch (Exception e) {
LOGGER.error("Error while saving local file: " + localFile + ": " + e, e);
throw e;
}
}
return dstFile;
}
I can see that there is more than 80% disk space available.
I've also checked for available inodes on the file system.
I don't know where might be the problem
Can someone please help me with this regard?

How to save a File to any specific path in Android

I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

How to create a directory, and save a picture to it in Android

This is a function I have written that tries to:
Create a folder with the users name
Save a .jpg inside of that
folder
The folder creation works fine, however when I try to save the pictures, they all save with the correct name, however they do not save in their intended folders. In other words, instead of having a folder containing a bunch of folders each containing one picture, I have one folder containing a bunch of empty folders, and a bunch of pictures all outside their folders (I can clarify if needed).
This is my code:
public void addToDir(List<Contact> list){
for(int i = 0; i < list.size(); i++){
String nameOfFolder = list.get(i).getName();
Bitmap currentBitmap = list.get(i).getBusiness_card();
String conName = Environment.getExternalStorageDirectory() + File.separator + "MyApp" + File.separator +
"Connected Accounts" + File.separator + nameOfFolder;
File conDir = new File(conName);
if (!conDir.mkdirs()) {
if (conDir.exists()) {
} else {
return;
}
}
try {
FileOutputStream fos = new FileOutputStream(conName + ".jpg", true);
currentBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
}
I suspect the problem is with the FileOutputStream path, but I am not sure how to set it so that it is set to the folder I just created.
Much appreciated
This is how to define mFileTemp
String state = Environment.getExternalStorageState();
File mFileTemp;
if (Environment.MEDIA_MOUNTED.equals(state)) {
//this is like that
//directory : any folder name/you can add inner folders like that/your photo name122412414124.jpg
mFileTemp = new File(Environment.getExternalStorageDirectory()+File.separator+"any folder name"+File.separator+"you can add inner folders like that"
, "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
}
else {
mFileTemp = new File(getFilesDir()+"any folder name"+
File.separator+"myphotos")+File.separator+"profilephotos", "your photo name"+System.currentTimeMillis()+".jpg");
mFileTemp.getParentFile().mkdirs();
This is how i save any image
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(mFileTemp);
copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
} catch (Exception e) {
Log.e("error save", "Error while creating temp image", e);
}
And copyStream method
public static void copyStream(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}

Java. Save File to Client side not working

I want to save File to a client side. How it can be done ?
When i start server localy all is good Files are saved # needed place, when run on server then files are saved on server side :( . Because System.getProperty("user.home") are returning :/root .
User select File from system and wants to open it. Code example:
mylog.pl("Blob in use + stop counter:" + stop);
File file = new File(SU.userHome + "/" + fileName);
mylog.pl("File maked ! Path:" + file.getAbsolutePath());
in = blob.getBinaryStream();
out = new FileOutputStream(file);
byte[] buff = new byte[4096];
int len = 0;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
try {
mylog.pl("Desktop Open!");
if (Desktop.isDesktopSupported())
{
Desktop.getDesktop().open(file);
}
else
{
mylog.pl("Desktop is not suported!");
//For other IS
DesktopApi.open(file);
}
}
catch (Exception e) {
mylog.pl("err # runtime" + e.getMessage());
}
Thanks ! Correct answers guaranteed !
//From server to client
final FileResource res = new FileResource(file);
FileDownloader fd = new FileDownloader(res);
p.open(res, "MyWindow", false);
file.delete();

How to get file.length of file on Internal storage? .length() doesn`t seem to work

trying to get length of file which from local storage. File exists 100% (because I even tried to create it straight before getting the length (and checked it exists). Code is as simple as:
try {
InputStream is = new FileInputStream("errorlog2.txt");
// Get the size of the file
long length = file.length();
// Close the input stream and return length
is.close();
return length;
}
catch (IOException e) {
Log.w(BaseHelper.TAG_MAIN_ACTIVITY, "bad stuff: ", e);
return 0;
in 100% cases it throws an exception. What might be the problem? What`s correct way to get length of local storage files?
thanks a lot!
UPDATE (full code) - file exists and readable, but no length :(
//creating file
String someFileName = "errlogtest.log";
try {
FileOutputStream fOut = openFileOutput(someFileName, Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("dsgaadfg0df9g0sdf90sg9058349 sdf");
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
//reading file
try {
FileInputStream fileToOpen = openFileInput(someFileName);
byte[] readerByte = new byte[fileToOpen.available()];
while (fileToOpen.read(readerByte) != -1) {
}
String fileContents = new String(readerByte);
fileContents.toString();
// next line works fine
Toast.makeText(getApplicationContext(), "FILE CONTENTS: " + fileContents, Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
Log.w("Reading file", "Unable to open file");
} catch (IOException e) {
Log.w("Reading file", "Error reading file");
}
// trying to get length
// simply not working:
File file = new File(someFileName);
long length2 = file.length();
Toast.makeText(getApplicationContext(), "FILE LENGTH:" + length2, Toast.LENGTH_LONG).show();
// shows zero and filenotfoundexception: /errlogtest.log
try {
RandomAccessFile raffile = new RandomAccessFile(new File(someFileName), "r");
long length = raffile.length();
Toast.makeText(getApplicationContext(), "FILE LENGTH:" + length, Toast.LENGTH_LONG).show();
catch (IOException e) {
Log.w("Reading file", "Error reading file", e);
}
help please
Depending on where you are creating the file then you'll need to provide a full path and not just a file name.
For example, if the file is being created using Context.openFileOutput(...) then you would use something like...
long length = new File(getFilesDir().getAbsolutePath() + "/errorlog2.txt").length();
Without opening the file you can get its length:
Method 1:
File file = new File("someFile.txt");
long length = file.length();
Method 2:
RandomAccessFile raf = new RandomeAccessFile(new File("someFile.txt"), "r");
long length = raf.length();

Categories

Resources