IOException on move file (FileUtils.moveFile) - java

I'm getting an IOException that is caught while trying to move a file.
public static void moveFile() {
String filePath = "C:/Users/newuser/inbound";
String archiveFolder = filePath.replaceAll("inbound", "archive");
File critLocation = new File(archiveFolder.concat("/crit"));
File sourceFolder = new File(filePath);
File[] listOfFiles = sourceFolder.listFiles();
for (File file : listOfFiles) {
if (file.getName().contains("crit")){
System.out.println("Moving crit file... " + file.getName());
try {
FileUtils.moveFile(file, critLocation);
} catch (FileAlreadyExistsException e) {
System.out.println("File " + file.getName() + " already exists.");
file.delete();
} catch (IOException exception) {
System.out.println("AN IO EXCEPTION HAS OCCURED");
}
}
}
}
I just want to use a filePath to move some files around. I also tried
FileUtils.moveFileToDirectory(file, sitLocation, false);
but to no avail.

Related

Simple file delete code is not working in Java [duplicate]

This question already has answers here:
Java 'file.delete()' Is not Deleting Specified File
(8 answers)
Closed 5 years ago.
Here is my code of deleting the pdf file
try {
File file = new File(docObjectId + ".pdf");
file.setWritable(true);
System.out.println(file.length());
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
It goes to the else part of the code.
PDF file is in project root folder and I am able to delete it manually. Scratching my head now.
Here is complete method. It might be due to some other reason
public Response getContractDocument(#PathParam("docid") String docObjectId) throws Exception {
DocumentumService documentumService = new DocumentumService(documentumConfigUtil);
DocumentumDocumentBean docDocumentBean = documentumService.getContractDocContent(docObjectId, true);
FileInputStream fileInputStream;
fileInputStream = new FileInputStream(docDocumentBean.getDocFile());
compressPdf(fileInputStream,docObjectId + ".pdf");
fileInputStream = new FileInputStream(docObjectId + ".pdf");
ResponseBuilder responseBuilder = Response.ok((Object) fileInputStream);
try {
File file = new File(docObjectId + ".pdf");
System.out.println(file.getAbsolutePath());
file.setWritable(true);
System.out.println(file.length());
File d = new File(file.getAbsolutePath());
if (d.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch(Exception e) {
e.printStackTrace();
}
return responseBuilder.build();
}
My experience is with windows. The reason that a file won't delete is always the same. Some object has a connection to the file and is holding it open. In this case, it looks like it might be fileInputStream.
Try this before you attempt to delete:
fileInputStream.close();
Change if(file.delete) to
try {
file.delete();
System.out.println("file deleted");
} catch(IOException e) {
System.out.println("file not deleted");
}
The exception may not be accurate.
First, check if the file exist or not and then delete it.
Kindly use the below code. Its working fine and is very clear approach for deletion. I hope it would help.
public static void main(String[] args) {
try{
File file = new File("C:/Users/Tehmina Yaseen/Documents/NetBeansProjects/FileDeletion/src/filedeletion/Myfile.pdf");
if (file.exists()) {
file.delete();
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the output:

Property file is returning as null in Java

I am trying to read some property from the properties file, but my code is not reading the property file. The properties file is in some folder in my machine.
Here is my code:
public String getproperty(){
String extension="";
Properties prop = new Properties ();
String propname = "\\"+Any location in your machine+"\\fileExtension.properties";
Logger.debug("ReadFiles", " ----Property file path---- "+ propname, null);
ip = getClass().getClassLoader().getResourceAsStream(propname);
Logger.debug("ReadFiles", " ----ip value ---- "+ip, null);
try {
if(ip != null){
prop.load(ip);
Logger.debug("ReadFiles", " ----Property file loaded---- ", null);
}
extension = prop.getProperty("fileExt");
Logger.debug("ReadFiles", " ----Property = " + extension, null);
} catch (IOException e) {
Logger.error("ReadFiles", " ----Error while loading property file---- ", null);
e.printStackTrace();
}
finally{
try {
ip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return extension;
}
I am creating a jar placing it in lib folder of server (installed in my machine) and placing the properties file in my machine and given the same path in code. I have tried with absolute path and without absolute path.
Please try this example that uses an absolute path to the properties file.
package com.company;
import java.io.*;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("/home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties");
prop.load(input);
String extension = prop.getProperty("fileExt");
System.out.println("ReadFiles ----Property = " + extension);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Test
cat /home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties
#Mon Dec 26 17:31:30 CET 2016
dbpassword=password
database=localhost
dbuser=foobar
fileExt=.xml⏎
Run the program
ReadFiles ----Property = .xml

How to connect with Azure cloud (blob storage) using dasein API

Can anyone help me with example or sample? I need to get & put files on the blob storage
I have managed to code following,
try {
CloudProvider provider = (CloudProvider) Class.forName("org.dasein.cloud.azure.Azure").newInstance();
ProviderContext providerContext = new ProviderContext("DEV","West US");
//providerContext.setStorage("");
providerContext.setStorageAccountNumber("mypackages");
providerContext.setStoragePublic("XXX".getBytes());
providerContext.setEndpoint("http://XXX.blob.core.windows.net/");
providerContext.setStorageX509Key("YYY".getBytes());
provider.connect(providerContext, provider);
System.out.println("here "+provider.testContext());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
On executing above code I am getting NPE as below
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
org.dasein.cloud.InternalException: java.lang.NullPointerException
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:64)
at org.dasein.cloud.azure.AzureMethod.getClient(AzureMethod.java:386)
at org.dasein.cloud.azure.AzureMethod.getAsStream(AzureMethod.java:124)
at org.dasein.cloud.azure.Azure.testContext(Azure.java:258)
at com.gehcit.dasein.App.main(App.java:27)
Caused by: java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
at org.dasein.cloud.azure.AzureX509.<init>(AzureX509.java:58)
... 4 more
This Works for me:
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;"
+ "AccountName=<Your accountname>;"
+ "AccountKey=<Your key>";
public static synchronized String upLoadSelected(String containername, String path, String directory, String pathPartRemover) {
List<File> filListe = new ArrayList<>();
if (storageConnectionString.isEmpty() != true) {
String respons = "";
try {
CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString);
CloudBlobClient serviceClient = account.createCloudBlobClient();
CloudBlobContainer container = null;
String source = "" + path;
container = serviceClient.getContainerReference("" + containername);
container.createIfNotExists();
String temp = "" + directory;
filListe = listf(source);
for (File file : filListe) {
if (file.isDirectory() == true && file.getParentFile().getName().equalsIgnoreCase(temp) != true) {
temp = (temp + "\\" + file.getName());
}
if (file.isDirectory() != true) {
CloudBlockBlob blob = container.getBlockBlobReference("" + file.getCanonicalPath().replace("" + pathPartRemover, ""));
File sourceFile = new File("" + file.getAbsolutePath());
blob.upload(new FileInputStream(sourceFile), sourceFile.length());
}
}
} catch (FileNotFoundException fileNotFoundException) {
respons = respons + "FileNotFoundException encountered: " + fileNotFoundException.getMessage();
} catch (StorageException storageException) {
respons = respons + "StorageException encountered: " + storageException.getMessage();
} catch (IOException e) {
respons = respons + "IOexception encountered: " + e.getMessage();
} catch (URISyntaxException e) {
respons = respons + "URIexception encountered: " + e.getMessage();
} catch (InvalidKeyException ex) {
respons = respons + "InvalidKeyException encountered: " + ex.getMessage();
}
return respons;
}
return "No connection";
}
public static synchronized List<File> listf(String directoryName) {
File directory = new File(directoryName);
List<File> resultList = new ArrayList<>();
File[] fList = directory.listFiles();
resultList.addAll(Arrays.asList(fList));
for (File file : fList) {
if (file.isFile()) {
} else if (file.isDirectory()) {
resultList.addAll(listf(file.getAbsolutePath()));
}
}
return resultList;
}

Saving files doesn't save a file

I'm creating a program that writes an error log to a file, but when I ask to save that file, just nothing happens (not even exceptions). What do I do wrong?
"Save" button actionListener:
public void actionPerformed(ActionEvent arg0) {
String savePath = getSavePath();
try {
saveFile(savePath);
} catch (IOException e) {
e.printStackTrace();
}
}
And the three file methods:
private String getSavePath() {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(this);
return fc.getSelectedFile().getAbsolutePath();
}
private void saveFile(String path) throws IOException {
File outFile = createFile(path);
FileWriter out = null;
out = new FileWriter(outFile);
out.write("Hey");
out.close();
}
private File createFile(String path) {
String fileName = getLogFileName(path);
while (new File(fileName).exists()) {
fileCounter++;
fileName = getLogFileName(path);
}
File outFile = new File(fileName);
try {
outFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return outFile;
}
private String getLogFileName(String path) {
return "enchantcalc_err_log_" + fileCounter + ".txt";
}
Your getLogFileName(...) function is not doing anything with the path you feed it. Therefore, you are trying to write the file to just enchantcalc_err_log_#.txt (with no actual path). Try this instead:
private String getLogFileName(String path) {
return path + "enchantcalc_err_log_" + fileCounter + ".txt";
}
You are probably just not finding the file.
At the end of your saveFile, try this: After
out.close();
Put a line, like this:
out.close();
System.out.println("File saved to: "+outFile.getAbsolutePath());
You'll then get the mistery path where it was saved.

Copied android db file is empty

I'm trying to copy an android db file from my application folder to another one on SD card. And from DDMS file explorer i can notice that the copied file size is 0. This is my code bellow.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
return false;
}
}
public void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
Is it a permission issue? Thanks for help.
#piyush
Thanks for the try/catch notice. I found the error after adding a log trace in boolean copyDBFile() method at catch block.
public boolean copyDBFile(){
File dbFile =new File(Environment.getDataDirectory() + DB_PATH);
File exportDir = new File(Environment.getExternalStorageDirectory()
+ "/BACKUP_DIR");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("Sarelo", "Error creating file", e);
return false;
}
}
My DB_PATH was already set to /data/data/package/databases/data.db and added to Environment.getDataDirectory() the dbFile result to /data/data/data/package/databases/data.db
That's the big mistake! Thanks all for help :)
try using outChannel.force(true); before using the transferTo(...);

Categories