java.io.IOException: Failed to delete original file - java

I was trying to move file using move file method .but getting this error
"java.io.IOException: Failed to delete original file"
this is my code.
this is for file move without error
public void moveWithoutError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound/");
File dest = new File("D:/Archive/");
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File sourceFile = new File(x);
File destnFile = new File(y);
try{
FileUtils.moveFile(sourceFile, destnFile);
System.out.println("Moved file:"+y);
}catch(Exception e){
System.out.println("Unable to move file:"+y);
System.out.println(e);
e.printStackTrace();
}
break;
}
}
}
This code is written for moving the file with containing error
public void moveWithError(String fileName){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String ts = dateFormat.format(date);
File source = new File("D:/Inbound\\");
File dest = new File("D:\\Error\\"); /
for (File file : source.listFiles()) {
String x = (source + "/" + file.getName());
String y = (dest + "/" + addTimestamp(file.getName(), ts));
if(file.getName().equals(fileName)){
File f1 = new File(x);
if(f1.renameTo(new File(y))){
System.out.println(" moved: " + y);
} else {
System.out.println("unable to move: " + y);
}
break;
}
}
}
This code is used to add timestamp to moved file
public static String addTimestamp(String name, String ts) {
int lastIndexOf = name.lastIndexOf('.');
return (lastIndexOf == -1 ?
name + "_" + ts
:
name.substring(0, lastIndexOf) + "-" + ts +
name.substring(lastIndexOf))
.replaceAll("[\\/:\\*\\?\"<>| ]", "");
}
}
while executing this code exception come
abd exception is
"java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812121814.xlsx'"
Note - this file is nor open neither accessing by other process
Please help :(
Exception
java.io.IOException: Failed to delete original file 'D:\Inbound\Testdata.xlsx' after copy to 'D:\Archive\Testdata-20140812130655.xlsx'
at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2664)
at CRP.MoveFile.moveWithoutError (MoveFile.java:77)
at CRP.CRPDAO.callMoveFile (CRPDAO.java:562)
at CRP.CRP_FileDependency.main (CRP_FileDependency.java:163)

Related

Why doesn't the file get deleted and renamed?

I have two models in my program, Bus and Learner.
Each is stored in a txt file, name Busses.txt and Learners.txt, respectively.
I am experiencing an issue where the method to delete a learner entry works, but the method to delete a bus entry does not, even though the code is practically identical.
Learner delete method:
public void deleteLearner(String ID) {
removeBlankLines("Learners.txt");
File oldFile = new File("Learners.txt");
File tempFile = new File("tempFile.txt");
String removeKey = ID;
String LearnerID;
String nameSurname;
boolean status;
String busOfLearner;
String line;
String lineToKeep;
try {
Scanner scFile = new Scanner(new File("Learners.txt"));
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line).useDelimiter("#");
LearnerID = scLine.next();
nameSurname = scLine.next();
status = scLine.nextBoolean();
if (scLine.hasNext()) {
busOfLearner = scLine.next();
} else {
busOfLearner = "";
}
if (!LearnerID.equalsIgnoreCase(removeKey)) {
lineToKeep = LearnerID + "#" + nameSurname + "#" + status + "#" + busOfLearner + "\n";
FileWriter fWriter = new FileWriter(tempFile,true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(lineToKeep);
bWriter.close();
fWriter.close();
}
scLine.close();
}
scFile.close();
boolean successfulDelete = oldFile.delete();
File transfer = new File("Learners.txt");
boolean successfulRename = tempFile.renameTo(transfer);
}
catch (Exception e) {
System.out.println("An error has occured deleting a learner record " + e);
}
}
Delete bus method:
public void deleteBus(String removeBusName) {
removeBlankLinesBus("Busses.txt");
File oldFile = new File("Busses.txt");
File newFile = new File("NewBusFile.txt");
String deleteKey = removeBusName;
String currentBusName;
int currentNumSeats;
String currentPickLocation;
String currentDropLocation;
String currentPickTime;
String currentDropTime;
String line;
String lineToKeep;
try {
Scanner scFile = new Scanner(new File("Busses.txt"));
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line).useDelimiter("#");
currentBusName = scLine.next();
currentNumSeats = scLine.nextInt();
currentPickLocation = scLine.next();
currentDropLocation = scLine.next();
currentPickTime = scLine.next();
currentDropTime = scLine.next();
if (!currentBusName.equalsIgnoreCase(deleteKey)) {
lineToKeep = currentBusName + "#" + currentNumSeats + "#" + currentPickLocation + "#" + currentDropLocation + "#" + currentPickTime + "#" + currentDropTime + "\n";
FileWriter fWriter = new FileWriter(newFile,true);
BufferedWriter bWriter = new BufferedWriter(fWriter);
bWriter.write(lineToKeep);
bWriter.close();
fWriter.close();
}
scLine.close();
}
scFile.close();
boolean successfulDelete = oldFile.delete();
File transfer = new File("Busses.txt");
boolean successfulRename = newFile.renameTo(transfer);
}
catch (Exception e) {
System.out.println("An error has occured deleting " + removeBusName + " from the file: " + e);
}
}
Problem:
With the delete bus method, the old file doesn't get deleted and the temporary or new file doesn't get renamed to the original file.
I am very confident that all files, streams, scanners, etc. are closed, as it is exactly the same as I did in the delete learner method, which does work and the files are deleted and renamed in the learner delete method as it should.
Assistance would be greatly appreciated.
EDIT: Implementation of methods:
Learner:
System.out.println(myController.PrintLearnerArr(myController.LoadLearner("Learners.txt")));
String delete = "0210045112055";
myController.deleteLearner(delete);
System.out.println(myController.PrintLearnerArr(myController.LoadLearner("Learners.txt")));
Bus:
System.out.println(myController.PrintBusArr(myController.LoadBus("Busses.txt")));
String deleteKey = "deleteme";
myController.deleteBus(deleteKey);
System.out.println(myController.PrintBusArr(myController.LoadBus("Busses.txt")));

Problem with CSV file creation in java with opencsv

I am trying to write a data from database to a csv file via java thread. For writing i am making use of OPENCSV jar. The problem i am facing is that sometimes in csv file values get corrupted like shown below in line 1 and 4.
I have no idea as to why this is happening. Values coming from the database are all ok (as can be seen in the logs) but in csv file its not.
[E[EcoUnit 01] [Segment B/1] [2017-12-29 22:13:23.047] [ventilation air humidity] [70.18]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:21:36.583] [ventilation air humidity] [69.65]
[EcoUnit 01] [Segment B/1] [2017-10-25 22:22:36.59] [ventilation air humidity] [69.33]
[EcoUnit 01] [Segment B/017-11-14 12:02:48.013] [ventilation fan] [30]
I would be really grateful if anyone can let me suggest why this is happening.
Code is as follows: -
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
Adding complete code of the function responsible for creating file and writing into it.
public void createAndFillFile(String startDateStr, String endDateStr, int fileNumber,SolrDocumentList results){
try{
String startDateParts[] = startDateStr.split(" ");
String startDate = startDateParts[0];
String endDateParts[] = endDateStr.split(" ");
String endDate = endDateParts[0];
if(fileNumber == 1){
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss") ;
String currentDate = dateFormat.format(date); //This line can be removed and in below line directly can be used
zipFile = currentDate + ".zip";
dir = new File("C:" + File.separator + "EcotronDownloadable" + File.separator + currentDate);
dir.mkdir();
path = dir.getAbsolutePath() + File.separator ;
file = new File(path+ startDate + "_" + endDate + "_" + fileNumber + ".csv");
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
}
synchronized(file){
for (SolrDocument doc : results) {
List<String> values = new ArrayList<String>();
Thread.sleep(1);
long fileLength = file.length();
if(fileLength<maxFileSize){
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
else{
fw.flush();
fw.close();
// writer.close();
j = j + 1;
file = new File(path + startDate + "_" + endDate + "_" + j + ".csv") ;
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
//log.trace(values);
writer.writeNext(values.toArray(new String[]{}));
}
}
}
// fw.flush();
// fw.close();
// writer.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
``
You might have two FileWriter instances (in different threads) pointing to the same file and writing at same time.
try this:
synchronized (file)
{
List<String> values = new ArrayList<String>();
fw = new FileWriter(file);
writer = new CSVWriter(fw);
writer.writeNext(headers);
values.add(doc.getFieldValue("Unit_Label").toString());
values.add(doc.getFieldValue("Segment_Label").toString());
values.add("[" + doc.getFieldValue("datestring").toString() + "]");
values.add(doc.getFieldValue("Item_Label").toString());
values.add(doc.getFieldValue("Value").toString());
writer.writeNext(values.toArray(new String[]{}));
}

java- resize image on ftp by thumbnailator library

I am uploading image from url on ftp by this code.
Image uploaded successful but when i try to resize uploaded image get error as the follows.
String imageUrl = "http://www.totaldesign.ir/wp-content/uploads/2014/11/hamayesh.jpg";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftp_server, ftp_port);
ftpClient.login(ftp_user, ftp_pass);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
// APPROACH #2: uploads second file using an OutputStream
URL url = new URL(imageUrl);
//**************select new name for image***********/
//get file extention
File file = new File(imageUrl);
String ext = getFileExtension(file);
//get file name from url
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
//create new image name for upload
String img_name = "simjin.com_" + fileNameWithoutExtn;
//get current year time for image upload dir
Date date = new Date();
DateFormat yeae = new SimpleDateFormat("yyyy");
String current_year = yeae.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory(current_year);
int dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory(current_year);
System.out.println("created folder: " + current_year);
}
//get current month time for image upload dir
DateFormat month = new SimpleDateFormat("MM");
String current_month = month.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory("/" + current_year + "/" + current_month);
dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory("/" + current_year + "/" + current_month);
System.out.println("created folder: " + "/" + current_year + "/" + current_month);
}
String uploadDir = "/" + current_year + "/" + current_month;
//rename image file if exist
boolean exists;
String filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
System.out.println("old file path=> " + exists);
//Rename file if exist
int i = 0;
while (exists) {
i++;
img_name = "simjin.com_" + fileNameWithoutExtn + i;
filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
//break loop if file dont exist
if (!exists) {
break;
}
}
System.out.println("new file path=> " + filePath);
//set image name in array for return
result[0] = img_name;
//*************end select new name for image**********/
System.out.println("ftpClinet Replay Code=> " + ftpClient.getStatus());
//Start uploading second file
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = ftpClient.storeFileStream(filePath);
System.out.println("outputStream Status=> " + outputStream);
byte[] bytesIn = new byte[10240];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
after success upload. I want to resize image by thumbnailator:
if (completed) {
System.out.println("The file is uploaded successfully.");
String new_img_name = uploadDir + "/" + img_name + "-150x150" + "." + ext;
OutputStream os = ftpClient.storeFileStream(filePath);
Thumbnails.of(image_url).size(150, 150).toOutputStream(os);
}
in this section get this error:
OutputStream cannot be null
Where is my wrong? And how to fix it?

Retrieving the full class path

I am trying to retrieve the full file path from the classes that have been edited. I can retrieve the comments, version number, author and date but can't seem to get the full file path that has been edited when more than one class has been included into the project.
I use these to retrieve the Comments and Author:
String comments = pc.getPendingChanges().getComment();
System.out.println("Comments: " + comments);
String author = pc.getPendingChanges().getAllPendingChanges()[0].getPendingSetOwnerDisplay();
System.out.println("Author: " + author);
I use this to retrieve the path:
String fileName = pc.getPendingChanges().getAllPendingChanges()[0].getLocalItem();
System.out.println("FileName: " + fileName);
but I only get this output:
FileName: C:\VS2013\Plugin\PluginTest\HelloWorld.classpath
I need to display the full path with the class name eg
FileName: C:\VS2013\Plugin\PluginTest\HelloWorld.Test.java
Full method displayed below:
#Override
public PolicyFailure[] evaluate(PolicyContext context)
throws PolicyEvaluationCancelledException {
final PendingCheckin pc = getPendingCheckin();
final List<PolicyFailure> failures = new ArrayList<PolicyFailure>();
final WorkItemCheckinInfo[] AssociatedWorkItems = pc.getWorkItems().getCheckedWorkItems();
WorkItem AssociatedCodeReview = null;
String failureReason = "";
for (int i=0; i<AssociatedWorkItems.length; i++) {
AssociatedCodeReview = AssociatedWorkItems[i].getWorkItem();
if (AssociatedCodeReview.getType().getName() == "Code Review") {
break;
}
}
if (AssociatedCodeReview != null) {
if (AssociatedCodeReview.getFields().getField("System.State").getValue()
.toString().equals("Not Approved")) {
failureReason = "Code Review Work Item associated but that is not approved by expert";
failures.add(new PolicyFailure(failureReason, this));
}
} else {
String fileName = pc.getPendingChanges().getAllPendingChanges()[0].getLocalItem();
System.out.println("FileName: " + fileName);
String fileName2 = pc.getPendingChanges().getAllPendingChanges()[0].getServerItem();
System.out.println("FileName2: " + fileName2);
String[] fileName3 = pc.getPendingChanges().getAffectedTeamProjectPaths();
System.out.println("FileName3: " + fileName3[0]);
//System.out.println("Found " + pc.getPendingChanges().getAffectedTeamProjectPaths()[0] + " work items.");
String comments = pc.getPendingChanges().getComment();
System.out.println("Comments: " + comments);
String author = pc.getPendingChanges().getAllPendingChanges()[0].getPendingSetOwnerDisplay();
System.out.println("Author: " + author);
String version = String.valueOf(pc.getPendingChanges().getAllPendingChanges()[0].getVersion());
System.out.println("Version: " + version);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println("Date Time: " + dateFormat.format(date));
}
return failures.toArray(new PolicyFailure[failures.size()]);
}
It actually does work, it was an error with my Eclipse install.
String fileName = pc.getPendingChanges().getAllPendingChanges()[x].getLocalItem();

Java Path Files.copy rename if exists

just a simple question, with a hard (for me) to find answer :D. Here is my code (im going to try to translate the spanish part):
File carpetanueva = new File("C:"+File.separator+"sistema" + File.separator +
fechasal+File.separator+doc);
carpetanueva.mkdirs();
carpetanueva.setWritable(true);
rutadestino = ("c:"+File.separator+"sistema" +
File.separator + fechasal+File.separator +
doc+File.separator+"imagen.jpg");
//realizo la copia de la imagen desde el jfilechooser a su destino:
Path desde = Paths.get(rutaorigen);
Path hacia = Paths.get(rutadestino);
try {
Files.copy(desde, hacia);
JOptionPane.showMessageDialog(null,
"Se adjunto la planilla de ambulancia correctamente");
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "error: "+e.getLocalizedMessage());
}
I get "rutaorigen" (frompath) from a JFileChooser. And I create "rutadestino" (topath) by using some variables so this way i can give an order. The problem is.. .if directories and the file "imagen.jpg" already exists, it gives an error.. (exception).. How can i make to check if image already exists, and if it does, rename the new image to , for example, imagen2? I cant figure out code, because im a newbie, I did a research and couldnt find something like this! Thanks in advance :)
OK, here is a quick solution if src is a Path to the file you want to copy, dst a Path to the file you want to write, and newName a Path to the file you want to rename to:
if (Files.exists(dst))
Files.move(dst, newName);
Files.copy(src, dst);
Note that you can use the methods in Path to facilitate your path building: .resolve(), .resolveSibling(), .relativize().
Edit: here is a function which will return a suitable name given a directory (dir), a base filename baseName and an "extension" (without the dot) extension:
private static Path findFileName(final Path dir, final String baseName,
final String extension)
{
Path ret = Paths.get(dir, String.format("%s.%s", baseName, extension));
if (!Files.exists(ret))
return ret;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
ret = Paths.get(dir, String.format("%s%d.%s", baseName, i, extension));
if (!Files.exists(ret))
return ret;
}
throw new IllegalStateException("What the...");
}
I think this link will help How do I check if a file exists?
So for your case, probably do something like:
File toFile = new File(rutadestino);
if (toFile.exists()) {
// rename file
toFile.renameTo(new File("newFilePath/newName.jpg"));
} else {
// do something if file does NOT exist
}
Hope that helps! For more info, also check the Java Docs for File
sory late. but my code can help to litle bit.
public void copyFile(File source, File dest) throws IOException,
FileAlreadyExistsException {
File[] children = source.listFiles();
if (children != null) {
for (File child : children) {
if (child.isFile() && !child.isHidden()) {
String lastEks = child.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(dest.toString() + "\\"
+ child.getName().toString());
if (child.getName().contains(".")) {
if (temp.exists()) {
temp = new File(dest.toString()
+ "\\"
+ b.replace(lastEks.lastIndexOf("."),
lastEks.lastIndexOf("."), " (1)")
.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName());
}
if (temp.exists()) {
for (int x = 1; temp.exists(); x++) {
if (child.getName().contains(".")) {
temp = new File(b.replace(
temp.toString().lastIndexOf(" "),
temp.toString().lastIndexOf("."),
" (" + x + ")").toString());
} else {
temp = new File(dest.toString() + "\\"
+ child.getName() + " (" + x + ")");
}
}
Files.copy(child.toPath(), temp.toPath());
} else {
Files.copy(child.toPath(), temp.toPath());
}
} else if (child.isDirectory()) {
copyFile(child, dest);
}
}
}
}
features :
1. rename if file exist in the destination. example: document.doc if exist document (1).doc if exist document (2).doc if exist ...
2. copy all file from source (only file) to one folder in destination
The code below checks if the file already exists in destination, if it does, it appends #1 to file name just before the extension. If that file name also exists, it keeps appending #2,#3,#4... till the file name doesn't exist in destination. Since () and spaces create problems in Unix environment, I used # instead.
You can extend this and do a SUMCHECK if the file in destination with the identical name also has the same content and act accordingly.
Credit goes to johan indra Permana
String lastEks = file.getName().toString();
StringBuilder b = new StringBuilder(lastEks);
File temp = new File(backupDir.toString() + File.separator + file.getName().toString());
if (file.getName().contains(".")) {
if(temp.exists()) {
temp = new File(backupDir.toString() + File.separator +
b.replace(lastEks.lastIndexOf("."), lastEks.lastIndexOf("."),"#1").toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName().toString());
}
b = new StringBuilder(temp.toString());
} else {
temp = new File(backupDir.toString() + File.separator + file.getName());
}
if (temp.exists()) {
for (int x=1; temp.exists(); x++) {
if(file.getName().contains(".")) {
temp = new File (b.replace(
temp.toString().lastIndexOf("#"),
temp.toString().lastIndexOf("."),
"#" + x ).toString());
} else {
temp = new File(backupDir.toString() + File.separator
+ file.getName() + "#" + x );
}
}
Files.copy(file.toPath(), temp.toPath());
} else {
Files.copy(file.toPath(), temp.toPath());
}

Categories