Android : Copying a file to the internal storage. File not found - java

I'm trying to backup my database file on the internal storage :
File fromFile = new File(context.getDatabasePath("database.db").getPath());
FileChannel fromFileChannel = new FileInputStream(fromFile).getChannel();
File toFile = new File(context.getFilesDir() + "/database.db");
if (toFile.getParentFile() != null)
toFile.getParentFile().mkdirs();
FileChannel toFileChannel = new FileOutputStream(toFile).getChannel();
Log.i("LOG",fromFileChannel.transferTo(0, fromFileChannel.size(), toFileChannel)+"");
fromFileChannel.close();
toFileChannel.close();
The log returns "69632" without any error, so it looks like it worked.
The problem is that I can't find the file. And the /Android/data folder doesn't contain a folder with my app package name. What am I doing wrong?

Use
File toFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Android/data" + File.separator + context.getPackageName() + File.separator + "/database.db");
context.getFilesDir() will give you the directory private to your app, so the files in that will not be available to other apps.

Related

Java Apache FTPClient most downloaded files are empty or missing

This is my code that is supposed to download entire FTP directory to a local folder. It does it well, but most of the files are 0KB in size. Only JSON files seem to contain all their data.
Things I tried:
Changing FTP file type with client.setFileType("FTP.BINARY_FILE_TYPE");
Using OutputStream instead of FileOutputStream
Code:
public static void copyFolder(File destination, FTPFile sourceFile, FTPClient ftpClient) throws IOException{
if (!sourceFile.isDirectory()) {
//copy file
File downloadFile = new File(destination + "/"+ sourceFile.getName());
String remoteFile = sourceFile.getName();
FileOutputStream outputStream = new FileOutputStream(downloadFile);
System.out.println(remoteFile);
System.out.println(downloadFile.getPath());
boolean success = ftpClient.retrieveFile(remoteFile, outputStream);
if(success) {
System.out.println("Retrieved " + remoteFile);
}
outputStream.close();
}else{
//loop through a subdirectory
ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory() + "/" + sourceFile.getName());
System.out.println(ftpClient.printWorkingDirectory());
FTPFile[] contents = ftpClient.listFiles(ftpClient.printWorkingDirectory());
File newDest = new File(destination + "/" + sourceFile.getName());
if(!newDest.exists()){
newDest.mkdir();
}
for(FTPFile file : contents){
copyFolder(newDest, file, ftpClient);
}
return;
}
}
How to get the transfer correctly?
log from ftp
tree of the ftp directory
tree of downloading directory
Trying to download it on the same computer ended with losing connection a few times - between and during file downloads. Also it seems that few files are downloaded. I will change the title of question to be more specific.
Only two files are being copied for some reason – https://pastebin.com/XNWqRMDj They are not empty.
The problem is your changeWorkingDirectory call. It's failing most of the time.
ftpClient.changeWorkingDirectory(ftpClient.printWorkingDirectory() + "/" + sourceFile.getName());
It should be:
ftpClient.changeWorkingDirectory(destination + "/" + sourceFile.getName());
For a complete working code for downloading FTP folders in Java, see:
Download all folders recursively from FTP server in Java

space is replaced by %20 in file path while creating file and file is created at new location

I have installed my software in below mention path.
i am getting resulting path of directory created at different location as my installation path contains space. can some one help me how to resolve this issue.
installation path :
/home/test/glh/QA oist/
expected endpoint reference directory :
/home/test/glh/QA oist/server/Tomcat/webapps/ibis/WEB-INF/services
resulting endpoint reference directory :
/home/test/glh/QA%20oist/server/Tomcat/webapps/ibis/WEB-INF/services
File repDir = new File(axisConf.getRepository().getFile());
String serviceName = IISUtilsHandler.replaceChars(module.getModuleName(), " ", "");
File serviceNameDir = new File(repDir + File.separator + "services" + File.separator + serviceName);
if ((moduleProperties.getBoolProperty("ValidateResponse", false) || moduleProperties.getBoolProperty("ValidateRequest", false))
&& moduleProperties.containsProperty("SchemaFileGenerationError")) {
String schemaGenerationError = moduleProperties.getProperty("SchemaFileGenerationError");
throw new IException("WebServiceConnector.Deploy.ErrorBecauseSchemaGenerationFailed", schemaGenerationError);
}
File serviceDir = new File(serviceNameDir, "META-INF");
if (!serviceDir.mkdirs()) {
throw new InubitException("CreateDirError", serviceDir.toString());
}
IISFileHandler.writeStringToFile(serviceDir + File.separator + "services.xml", createServiceXml(moduleProperties, module));
IISFileHandler.writeStringToFile(serviceDir + File.separator + "service.wsdl", moduleProperties.getProperty("WsdlData"));
Please share more details and sample code you are using to get/generate installation file path.
However you can add below java code to replace special character (%20) with space on the fly
File dir = new File( new URI(installation_path.replaceAll(" ", "%20")) );

How to move an already moved file to new directory

I am trying to move a single File between folders. I use file.renameTo() to move my file.
//moving the file to new folder
//this is success
boolean fileMoveCompleted = finalFileToProcess
.renameTo(new File(processingFolderName
+ File.separator + finalFileToProcess.getName()));
//now trying to move the renamed file to another folder
//this is failing
fileMoveCompleted = finalFileToProcess
.renameTo(new File(successFolderName
+ File.separator
+ finalFileToProcess.getName()));
After the first renameTo the file path still points to the older path. Is there any way I can move the same file to another directory ?
You need to keep the first target file of renameTo as reference and rename that one.
File processing = new File(processingFolderName
+ File.separator
+ finalFileToProcess.getName());
boolean fileMoveCompleted = finalFileToProcess.renameTo(processing);
File finished = new File(successFolderName
+ File.separator
+ finalFileToProcess.getName());
fileMoveCompleted = processing.renameTo(finished);
But as File.renameTo's JavaDoc suggests, you should better use Files.move.

Save to desktop without the exact path

I want to save a file in my desktop. So I have
FileOutputStream out = new FileOutputStream(new File("C:\\path_to_Dekstop\\print.xls"));
and it works. But I want to save the file without put the exact path to the desktop. I searched it and I found similar questions and I came up with this solution:
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop));
but I got an error
java.io.FileNotFoundException: C:\Users\nat\Desktop (Access is denied)
pathToDesktop represents the directory of the Desktop, you should supply a file name to write to
FileOutputStream out = new FileOutputStream(new File(desktopDir, "File to be written to"));
Which will place the "File to be written to" on the desktop
You can't write directly to Desktop as its a folder but not a file. You need to write to a file. DO something like thi s:-
File desktopDir = new File(System.getProperty("user.home"), "Desktop");
System.out.println(desktopDir.getPath() + " " + desktopDir.exists());
String pathToDesktop = desktopDir.getPath();
FileOutputStream out = new FileOutputStream(new File(pathToDesktop+System.getProperty("file.separator")+"print.xls"));
This will write to print.xls in Desktop.

Add suffix to filename if file already exist instead of overwriting it

I'm saving an uploaded file as below:
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName());
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();
But my question is when upload once file same old file in folder D:/FileUpload. In above function it will delete old file. Example first time, i upload file : test.doc (old file). Then i upload another file with same name : test.doc (new file). At folder FileUpload will has one file is test.doc (new file). I want function will process similar in window OS is : new file will be test (2).doc. How can i process it ? And all cases : D:/FileUpload have many file : test.doc, test (1).doc, test (2).doc, test (a).doc,...... I think we just check with format ....(int).doc. That new file will be :
test (3).doc (ignore test(a).doc)
Maybe you're looking for something like this? I list the files in your directory, compare the names of each to the name of your file. If the names match, increment a count. Then, when you come to create your file, include the count in its name.
UploadItem item = event.getUploadItem();
File dir = new File("D:/FileUpload");
if (!dir.exists()) {
dir.mkdir();
}
String [] files = dir.list();
int count = 0;
for(String file : files) {
if (file.startsWith(item.getFileName()) {
count++;
}
}
File bfile = new File("D:/FileUpload" + "/" + item.getFileName() + "(" + count + ")");
OutputStream outStream = new FileOutputStream(bfile);
outStream.write(item.getData());
outStream.close();

Categories