I want to delete file located in local machine, comparing to server machine.
My example :
import java.io.*;
public static void main(String[] args) throws Exception {
Set<String > lmd5 = new HashSet<String>();
lmd5.add("4be1babb2f8cac64d96f8052c0942130");
lmd5.add("a7514d56f233a434c7066176933d708d");
lmd5.add("d41d8cd98f00b204e9800998ecf8427e");
lmd5.add("674e3b94be9ed5db8bafe75808385de1");
Set<String > dmd5 = new HashSet<String>();
dmd5.add("4be1babb2f8cac64d96f8052c0942130");
dmd5.add("a7514d56f233a434c7066176933d708d");
dmd5.add("d41d8cd98f00b204e9800998ecf8427e");
if(lmd5.equals(dmd5)){
System.out.println("OK");
}
else{
lmd5.removeAll(dmd5);
System.out.println("Obsoletes Files To Delete : " + lmd5);
File[] paths = baseModDirectoryFile.listFiles();
for(File path:paths){
FileInputStream fis = new FileInputStream(path);
String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
if(lmd5.contains(md5) ){
File foundFile = path;
System.out.println("Obsolete File Found !");
try{
if(foundFile.delete()){
System.out.println("Obsolete File Deleted !");
}
else{
System.out.println("Obsolete File Not Deleted : Error !");
}
}catch(Exception e){
e.printStackTrace();
}
}
else{
continue;
}
}
}
}
In my output console, I have the message "Obsoletes Files Found" which appears, but after that I have the message : "Obsolete File Not Deleted". I believe I arrive too late in the function to delete the file, as all files have already been checked.
Maybe I have to review this position but I would like to get some advise.
Thank you !
What is the value of foundFile.delete()?
Do you have enough permission to delete file?
May be your file is being locked by your FileInputStream?
Related
So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?
You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.
Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest
Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}
I am using Eclipse and the Java Library: java.io.FileInputStream;
My script cannot find a file that I want to assign to a variable using the constructor FileInputStream even though the file is in the Working directory.
Here is my code:
package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
public static void main(String [] args){
//verify what the working directory is
String curDir = System.getProperty("user.dir");
System.out.println("Working Directory is: "+curDir);
//verify the file is recognized within within the code
File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
} else {
System.out.println("File does not exist");
}
//Assign the file to src
File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
System.out.println("SRC is now: "+src);
//Get Absolute Path of the File
System.out.println(src.getAbsolutePath());
FileInputStream fis = new FileInputStream(src);
}*
My output is (when i comment out the last line) is
"Working Directory is: C:\Users\wes\workspace\QTI_crud
Yes, File does exist
SRC is now: C:\Users\wes\workspace\QTI_crud\values.xlsx
C:\Users\wes\workspace\QTI_crud\values.xlsx"
When I don't comment out the last line, I get the error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"
Where have I gone wrong in my code? I'm pretty new to Java
Much thanks!
Major problem with the code is that you after you know that file do not exist on specified directory, you tried to read the file. Hence, it is giving you the error.
Refactor it to this
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
try {
FileInputStream fis = new FileInputStream(f);
//perform operation on the file
System.out.println(f.getAbsolutePath());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
Here as you can see, if file exists then you try to read the file. If it is not available you don't do anything.
I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
This question already has answers here:
Delete directories recursively in Java
(26 answers)
Closed 9 years ago.
Here is a code I tried:
import java.io.*;
public class file03 {
public static void main(String[] args) {
File f1 = new File("C:/tempo1/tempo");
f1.mkdirs();
File f2 = new File("C:/test");
if(!f2.exists()) {
f2.mkdir();
}
f1 = new File("C:/tempo1/kempo");
f1.mkdirs();
f1 = new File("C:/tempo1");
String[] t = {};
if(f1.exists()) {
t = f1.list();
System.out.println(t.length + " files found");
}
for(int i = 0; i < t.length; i++) {
System.out.println(t[i]);
}
try {
Thread.sleep(3000);
}
catch(Exception e) {}
f2.delete();
f2 = new File("C:/tempo1/test.txt");
try {
f2.createNewFile();
}
catch(Exception e) {}
try {
Thread.sleep(7000);
}
catch(Exception e) {}
File f3 = new File("C:/tempo1/renametesting.txt");
f2.renameTo(f3);
try {
Thread.sleep(5000);
}
catch(Exception e) {}
f3 = new File("C:/tempo1");
f3.delete();
}
}
what I noticed was that while the folder test gets deleted, the folder tempo1 doesn't get deleted. Is it because it contains other folders and files? If so, how can I delete it?
I am using BlueJ IDE.
A folder can not be deleted until all files of that folder are deleted.
First delete all files from that folder then delete that folder
This is code for deleting a folder..
You need to pass the path of the folder only
public static void delete(File file)
throws IOException {
if (file.isDirectory()) {
//directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : "+ file.getAbsolutePath());
} else {
//list all the directory contents
String files[] = file.list();
for (String temp : files) {
//construct the file structure
File fileDelete = new File(file, temp);
//recursive delete
delete(fileDelete);
}
//check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
// System.out.println("Directory is deleted : " + file.getAbsolutePath());
}
}
} else {
//if file, then delete it
file.delete();
// System.out.println("File is deleted : " + file.getAbsolutePath());
}
}
public class DeleteFolder {
/**
* Delete a folder and all content folder & files.
* #param folder
*/
public void rmdir(final File folder) {
if (folder.isDirectory()) { //Check if folder file is a real folder
File[] list = folder.listFiles(); //Storing all file name within array
if (list != null) { //Checking list value is null or not to check folder containts atlest one file
for (int i = 0; i < list.length; i++) {
File tmpF = list[i];
if (tmpF.isDirectory()) { //if folder found within folder remove that folder using recursive method
rmdir(tmpF);
}
tmpF.delete(); //else delete file
}
}
if (!folder.delete()) { //if not able to delete folder print message
System.out.println("can't delete folder : " + folder);
}
}
}
}
To delete folder having files , no need of loops or recursive search. You can directly use:
FileUtils.deleteDirectory(<File object of directory>);
This function will delete the folder and all files in it
You can use the commons io library FileUtils class :
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File)
"Deletes a directory recursively."
I am trying to save contents in file but first I want to search either file does exist or not. But the code I have written, every time it is returning true.
String fileName=FNameTextField.getText();
File file=new File(fileName);
if(file.exists()&& !file.isDirectory()) {
// It returns true if File or directory does exist
System.out.println("the file or directory you are searching does exist : " );
}else{
// It returns true if File or directory not exists
System.out.println("the file or directory you are searching does not exist : " );
}
Thanks.
Your logic seems to be all screwy, or at least I can't make heads or tails of it
if (file.exists()) {
if (file.isDirectory) {
System.out.println("Directory already exists");
} else {
System.out.println("File exists");
}
} else {
System.out.println("Could not find a file or directory matching your request");
}
Try using method...
file.isFile()
The javadoc says
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
Your logic checks if to see only if it is a file. It will NOT return true if a directory with the name exists as you imply in your print statements.
Make use of this examples which is adopt for you :
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
(or)
import java.io.*;
public class FileChecker {
public static void main(String args[]) {
File f = new File("c:\\mkyong.txt");
if(f.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
}
}
(or)
import java.io.*;
public class FileOrDirectoryExists{
public static void main(String args[]){
File file=new File("Any file name or
directory whether exists or not");
boolean exists = file.exists();
if (!exists) {
// It returns false if File or directory does not exist
System.out.println("the file or directory
you are searching does not exist : " + exists);
}else{
// It returns true if File or directory exists
System.out.println("the file or
directory you are searching does exist : " + exists);
}
}
}
1. First get all the files in the folder, and store it in an ArrayList.
Eg:
File f = new File("d:\\MyFolder);
File[] fArr = f.listFiles();
ArrayList<File> fList = new ArrayList<File>();
for ( File file : fArr){
if (file.isFile()){
fList.add(file);
}else{
continue;
}
}
2. Now use getName() method to check the file exists or not....
Assume you are looking for a file named "vivek.txt"
Eg:
boolean b = false;
for (File i : fList){
if ((i.getName).equals("vivek.txt")){
b = true;
break;
}
else{
continue;
}
}