How to upload file to Dropbox? - java

I want to upload a file to drop-box using a web-application. But the problem is that Java is asking the complete file path. What do I have to do? This is my code:
File inputFile = new File("D://New Text Document.txt");
System.out.println("inputFile.getAbsoluteFile(): " + inputFile);
FileInputStream inputStream = new FileInputStream("D://New Text Document.txt");
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
In the first line it is asking for the file path; how is this possible?

you can use relative path
File inputFile = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
more details here

The Dropbox Java Core SDK tutorial has the following code as a sample for uploading a file:
File inputFile = new File("working-draft.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/magnum-opus.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
In the sample above, in the first line, "working-draft.txt" is the local path to a local file. This needs to point to an existing local file. Your code has "D://New Text Document.txt" so you should first make sure there is actually a file there.
In the fourth line, "/magnum-opus.txt", the first parameter passed to uploadFile, is the desired remote path, that is, where in the Dropbox folder you want to upload the file to. The API requires remote paths be referenced relatively like this. The uploadFile method is documented here.

Related

Sub Directories under getCacheDir()

I'm trying to create sub directories in my apps cache folder but when trying to retrieve the files I'm getting nothing. I have some code below on how I created the sub directory and how I'm reading from it, maybe I'm just doing something wrong (well clearly I am lol) or maybe this isn't possible? (though I haven't seen anywhere that you can't). thank you all for any help!
creating the sub dir
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
File file2 = new File(file, each_filename);
Toast.makeText(getApplicationContext(), file2.toString(), Toast.LENGTH_SHORT).show();
stream = new FileOutputStream(file2);
stream.write(bytes);
reading from it
File file = new File(context.getCacheDir(), "SubDir");
File newFile = new File(file, filename);
Note note;
if (newFile.exists()) {
FileInputStream fis;
ObjectInputStream ois;
try {
fis = new FileInputStream(new File(file, filename));
ois = new ObjectInputStream(fis);
note = (Note) ois.readObject();
fis.close();
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
return note;
}
I've also tried with this and nothing
String file = context.getCacheDir() + File.separator + "SubDir";
I don't see anywhere in the code you posted where you actually create the sub-directory. Here's some example code to save a file in a sub-directory, by calling mkdirs if the path doesn't yet exist (some parts here need to be wrapped in an appropriate try-catch for an IOException, but this should get you started).
File cachePath = new File(context.getCacheDir(), "SubDir");
String filename = "test.jpeg";
boolean errs = false;
if( !cachePath.exists() ) {
// mkdir would work here too if your path is 1-deep or
// you know all the parent directories will always exist
errs = !cachePath.mkdirs();
}
if(!errs) {
FileOutputStream fout = new FileOutputStream(cachePath + "/" + filename);
fout.write(bytes.toByteArray());
fout.flush();
fout.close();
}
You need to make your directory with mkdir.
In your code:
File file = new File(getApplicationContext().getCacheDir(), "SubDir");
file.mkdir();
File file2 = new File(file, each_filename);

Can't delete file in java on windows ....?

I am trying to use file.delete() but it does not delete file ? I tested it on linux it delete files but on windows it does not delete file why..?
code :
private File getFiletobeUpload(File foto) {
boolean errorRename = true;
File uploadFile = null;
File testFile = foto;
String subdirname = this.checkDir(foto);
if (testFile.canWrite()) {
uploadFile = new File(AppConstants.PHOTOPATH + "/" + subdirname + "/" + testFile.getName());
try {
FileInputStream origStream = new FileInputStream(testFile);
FileOutputStream outStream = new FileOutputStream(uploadFile);
origStream.getChannel().transferTo(0, testFile.length(), outStream.getChannel());
origStream.close();
origStream = null;
outStream.close();
outStream = null;
} catch (Exception e) {
this.errorString += "error while writing to orig dir";
logger.error(e);
}
errorRename = !testFile.delete();
if (errorRename) {
this.errorString += "error while deleting the file";
}
}
testFile = null;
return uploadFile;
}
your code seems a bit odd, you are checking "testFile" for write access but then actually reading from it (FileInputStream). Is the first try/catch block running without exception? Maybe you should check if the file even exists:
System.out.println("File exists: "+testFile.exists());
errorRename = !testFile.delete();
Also if you just want to rename a file, use:
file.renameTo(File dest)
A general suggestion: consider using the classes in the java.nio package to your file IO if you can (not sure which version of Java you're running with) because the error handling is improved and you should be able to find a more specific reason for the failure based on the type of exception thrown and the exception message.
As per API, the disk-drive specifier - "/" for the UNIX root directory, and "\\" for a Microsoft Windows UNC pathname.
so for windows:
uploadFile = new File(AppConstants.PHOTOPATH + "\\" + subdirname + "\\" + testFile.getName());

How to create a folder and write a simple .txt file in that folder on Internal Storage on Android

I cant seem to get the following code to work; i've tried diffrent methods but none work, i wanna create a folder int he internal storage and a create and write to a simple .txt file within that folder. Can someone please provide a robust example of how to do it, and show me what i'm getting wrong
String DataIn = PhoneNumber + "," + dataLong + "," + dataLat;
FileOutputStream outputStream;
String filename = "LegionData";
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(DataIn.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Try this
String filename = "myfile";
File file = new File(context.getFilesDir(), filename);

java.io.FileNotFoundException:

I am Trying to Copy Single file from Source to Destination using Java but getting following Error message.
java.io.FileNotFoundException: Following is the method
public void copy_single(String source,String dest,String filename)
{
try
{ System.out.println(source + "" + filename);
System.out.println(dest + "" + filename);
File inputFile = new File(source+""+filename);
File outputFile = new File(dest+""+filename);
Process proc0 = Runtime.getRuntime().exec("chmod -R 777 "+inputFile+"");
proc0.waitFor();
Process proc1 = Runtime.getRuntime().exec("chmod -R 777 "+outputFile+"");
proc1.waitFor();
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
} catch(Exception e) {
e.printStackTrace();
System.out.println("Error: Operation failed!");
}
}
Output:-
/home/root/Tool/AAputDelta.sh
/home/root/Desktop/Sqa/BaseLine/Engine/AAputDelta.sh
java.io.FileNotFoundException: /home/root/Desktop/Sqa/BaseLine/Engine/AAputDelta.sh (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at java.io.FileOutputStream.<init>(FileOutputStream.java:145)
How to copy simple file using java.
Suspect that some or all of dest output path may not exist. If this is the case you could use File.mkdirs to build the path.
Also, rather than building the file from strings, would suggest allowing File handle all this, e.g.:
File inputFile = new File(source, filename);
File outputFile = new File(dest, filename);
Use apache commons FileUtils. Any of these should be sufficient
FileUtils.copyFile(File srcFile, File destFile)
FileUtils.copyFile(File srcFile, File destFile, boolean preserveFileDate)
FileUtils.copyFileToDirectory(File srcFile, File destDir)
FileUtils.copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate)
You can use FileUtils from commons-io :
http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html
or the Files from Java 7 :
http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
java.io.FileNotFoundException Means that some file was not found so check the values :
source
dest
filename
source+""+filename
dest+""+filename
If the file doesn't exist, the filesystem will try to create the file. If creation fails, Java will throw FileNotFountException.
Maybe you need add
File outputFile = new File(dest+""+filename);
if(!outputFile.exist())outputFile.createNewFile();

Error in Selecting multiple files into one zip and downloading the zip file?

<% // Set the content type based to zip
response.setContentType("Content-type:text/zip");
response.setHeader("Content-Disposition", "attachment; filename=mytest.zip");
// List of files to be downloaded
List files = new ArrayList();
files.add(new File("C:/first.txt"));
files.add(new File("C:/second.txt"));
files.add(new File("C:/third.txt"));
ServletOutputStream out1 = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out1));
for (Object file : files)
{
//System.out.println("Adding file " + file.getName());
System.out.println("Adding file " + file.getClass().getName());
//zos.putNextEntry(new ZipEntry(file.getName()));
zos.putNextEntry(new ZipEntry(file.getClass().getName()));
// Get the file
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (Exception E) {
// If the file does not exists, write an error entry instead of file contents
//zos.write(("ERROR: Could not find file " + file.getName()).getBytes());
zos.write(("ERROR: Could not find file" +file.getClass().getName()).getBytes());
zos.closeEntry();
//System.out.println("Could not find file "+ file.getAbsolutePath());
continue;
}
BufferedInputStream fif = new BufferedInputStream(fis);
// Write the contents of the file
int data = 0;
while ((data = fif.read()) != -1) {
zos.write(data);
}
fif.close();
zos.closeEntry();
//System.out.println("Finished adding file " + file.getName());
System.out.println("Finished adding file " + file.getClass().getName());
}
zos.close();
%>
this is my actualy program , want to zip multiple file and then downloading it , is wat i am doing the way is right or wrong , am new to JAVA programming , can you help me out ???
Your for loop should look like this:
for (File file : files) {
...
or
for (String file : files) {
...
The way you declared file variable, makes compiler assume it's an Object, and not a File instance. Thus, you get compilation error, because there is no FileInputStream constructor accepting an Object. The file must either be a File or a String containing absolute path to a file.
Another error is the way, you're passing file's name to the ZipEntry.
Using:
file.getClass().getName()
will result in "java.io.File" or "java.lang.String", and not the file name.
To set the proper name of the file, use File#getName().

Categories