I've got the following code to delete a folder and its contents but its only deleting the contents and not the folder. How can i change it to delete the folder as well?
private static void deleteCat(String catName) {
File fileToDel = new File("Catalogues/" + catName);
if (fileToDel.exists()) {
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
} else {
if (fileToDel.delete()) {
System.out.println("File " + fileToDel + " deleted");
} else {
System.out.println("Unable To Del " + fileToDel);
}
}
}
}
remove the else of line 10. fileToDel.delete() must be executed anycase.
When you're trying to delete a directory, you've not included the code to delete the directory itself
private static void deleteCat(String catName) {
File fileToDel = new File("Catalogues/" + catName);
if (fileToDel.exists()) {
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
fileToDel.delete();
}
//Always want to delete the given file, so remove the 'else'
if (fileToDel.delete()) {
System.out.println("File " + fileToDel + " deleted");
} else {
System.out.println("Unable To Del " + fileToDel);
}
}
}
It deletes only your content, because you don't delete the directories. Add at the end of your directoryroutine the command to delete your directory too.
if (fileToDel.isDirectory()) {
if (fileToDel.list().length > 0) {
for (String s : fileToDel.list()) {
deleteCat(catName + "/" + s);
}
}
fileToDel.delete(); //delete directory
} else ...
Also have a look at the apache commons-io lib (http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#deleteDirectory(java.io.File))
Related
I have a database connected that I am retrieving and storing local files and directories in. It works properly except when I run this segment, it will duplicate some of the results and store them. I believe the issue is in the way that I am grabbing them here, but I am not sure how to remedy it.
public static void Recursion(File dir, int dirid) {
for (java.io.File file : dir.listFiles()) {
if (file.isDirectory()) {
saveDir(dir, file);
} else if (file.isFile()) {
if (dirid == 0) {
saveDir(dir, file.getParentFile());
} // Begin Recursion, File
BoFile file1 = new BoFile();
file1.setFileName(file.getName());
file1.setFileType(file.getName().substring(file.getName().lastIndexOf('.') + 1).trim());
file1.setFileSize(new Long(file.length()).doubleValue() / 1024 + "MB");
file1.setFilePath(file.getPath());
file1.setDirNameId(dirid);
FileDAO fileDAO = new FileDAOImpl();
int id = fileDAO.insertFile(file1);
logger.info("New File: " + file.getName() + " ID = " + id);
}
}
}
private static void saveDir(File dir, File file) { // // Begin Recursion, Dir
Dir directory = new Dir();
directory.setDirName(file.getName());
directory.setDirNumberofFiles(dir.listFiles().length);
directory.setDirSize(new Long(dir.length()).doubleValue() / 1024 + "MB");
directory.setDirpath(dir.getPath());
DirDAO dirDAO = new DirDAOImpl();
int id = dirDAO.insertDir(directory);
logger.info("New Directory, " + file.getName() + " ID = " + id);
Recursion(file, id);
}
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}
I want to find the count of files inside the svn. i know how to check is it a file or directory.
try {
nodeKind = repository.checkPath("", -1);
} catch (SVNException ex) {
Logger.getLogger(Reassignscreen.class.getName()).log(Level.SEVERE, null, ex);
}
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
commitClient.doMkDir(new SVNURL[]{SVNURL.parseURIDecoded(url)}, "New Folder");
}
Like this is there any way to retrieve the count of files inside the svn.
Use this code it will help you,
public class DisplayRepositoryList{
static int xmlfilecount = 0;
static ArrayList<String> imagefoldercheck = new ArrayList<String>();
public static void displayrepositorytree(String url, String name, String password) {
xmlfilecount =0;
SVNSetupLibrary.setupLibrary();
SVNRepository repository = null;
try {
repository = SVNRepositoryFactory.create(SVNURL.parseURIEncoded(url));
} catch (SVNException svne) {
System.err.println("error while creating an SVNRepository for location '" + url + "': " + svne.getMessage());
// System.exit(1);
}
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(name, password);
repository.setAuthenticationManager(authManager);
try {
SVNNodeKind nodeKind = repository.checkPath("", -1);
if (nodeKind == SVNNodeKind.NONE) {
System.err.println("There is no entry at '" + url + "'.");
// System.exit(1);
} else if (nodeKind == SVNNodeKind.FILE) {
System.err.println("The entry at '" + url + "' is a file while a directory was expected.");
// System.exit(1);
}
System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
System.out.println("");
imagefoldercheck = new ArrayList<String>();
listEntries(repository, "");
} catch (SVNException svne) {
System.err.println("error while listing entries: "
+ svne.getMessage());
}
/*
* Gets the latest revision number of the repository
*/
long latestRevision = -1;
try {
latestRevision = repository.getLatestRevision();
} catch (SVNException svne) {
System.err.println("error while fetching the latest repository revision: "
+ svne.getMessage());
// System.exit(1);
}
System.out.println("");
System.out.println("---------------------------------------------");
System.out.println("Repository latest revision: " + latestRevision);
}
/*
* Initializes the library to work with a repository via
* different protocols.
*/
public static void listEntries(SVNRepository repository, String path)
throws SVNException {
Collection entries = repository.getDir(path, -1, null,
(Collection) null);
Iterator iterator = entries.iterator();
while (iterator.hasNext()) {
SVNDirEntry entry = (SVNDirEntry) iterator.next();
if (entry.getName().endsWith(".xml")) {
System.out.println(entry.getName() + " " + xmlfilecount);
xmlfilecount = xmlfilecount + 1;
imagefoldercheck.add(entry.getName());
}
System.out.println("imagefoldercheck --> "+imagefoldercheck);
/*
* Checking up if the entry is a directory.
*/
if (entry.getKind() == SVNNodeKind.DIR) {
listEntries(repository, (path.equals("")) ? entry.getName()
: path + "/" + entry.getName());
}
}
}
}
I am making an application for file uploading in Java using jSch. I want to put my file in different directories based on their creation date etc.
I have a main directory "/var/local/recordingsbackup/" in which I am creating other directories and putting data in them.
To achieve this:
I have to create Dir'y like
"/var/local/recordingsbackup/20140207/root/SUCCESS/WN/" and put
data in it.
I've tried this so far:
private void fileTransfer(ChannelSftp channelTarget, temp_recording_log recObj, String filePath) {
int fileNameStartIndex = filePath.lastIndexOf("/") + 1;
String date = new SimpleDateFormat("yyyyMMdd").format(recObj.getCalldate());
String fileName = filePath.substring(fileNameStartIndex);
String staticPath = "/var/local/recordingsbackup/";
String completeBackupPath = staticPath + date + "/" + recObj.getUsername() + "/" + recObj.getStatus() + "/" + recObj.getDisposition() + "/";
try {
InputStream get = SourceChannel.get(filePath);
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
channelTarget.mkdir(completeBackupPath); // error on this line
channelTarget.put(get, completeBackupPath + fileName);
}
} catch (SftpException e) {
log.error("Error Occured ======== File or Directory dosen't exists === " + filePath);
e.printStackTrace();
}
}
If I'm creating single dir like /var/local/recordingsbackup/ then no error occurs and files successfully uploaded.
Please help me in this...how can I create these Nested Directories???
Finally, I've done it.
This is how I got succeed :
try {
channelTarget.put(get, completeBackupPath + fileName);
} catch (SftpException e) {
System.out.println("Creating Directory...");
String[] complPath = completeBackupPath.split("/");
channelTarget.cd("/");
for (String dir : complPath) {
if (folder.length() > 0) {
try {
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.cd(folder);
} catch (SftpException e2) {
channelTarget.mkdir(folder);
channelTarget.cd(folder);
}
}
}
channelTarget.cd("/");
System.out.println("Current Dir : " + channelTarget.pwd());
channelTarget.put(get, completeBackupPath + fileName);
}
I don't think what you want to do is possible in the SFTP protocol. You will have to create each sub-directory in turn.
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
ch.mkdir(fullPath + folders[i]);
}
fullPath = fullPath + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
I used this implementation to create nested folders.
I tried not to use Exception. Keep in mind that filesystem is linux based.
The OP already found a solution but I wanted to append to it.
Simply I do mkdir if the folder that I wanted to create doesn't exist in "ls" result.
Correction of the previous script:
public static void mkdirs(ChannelSftp ch, String path) {
try {
String[] folders = path.split("/");
if (folders[0].isEmpty()) folders[0] = "/";
String fullPath = folders[0];
for (int i = 1; i < folders.length; i++) {
Vector ls = ch.ls(fullPath);
boolean isExist = false;
for (Object o : ls) {
if (o instanceof LsEntry) {
LsEntry e = (LsEntry) o;
if (e.getAttrs().isDir() && e.getFilename().equals(folders[i])) {
isExist = true;
}
}
}
if (!isExist && !folders[i].isEmpty()) {
// Add separator path
ch.mkdir(fullPath + "/" + folders[i]);
}
// Add separator path
fullPath = fullPath + "/" + folders[i] + "/";
}
} catch (Exception e) {
e.printStackTrace();
}
}
Another solution is execute shell command:
String remotePath = "fake/folders/recursive/on/sftp/server";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
// NOTE: the provided paths are expected to require no escaping
channel.setCommand("mkdir -p " + remotePath);
channel.connect();
while (!channel.isClosed()) {
// dir creation is usually fast, so only wait for a short time
Thread.sleep(SHORT_WAIT_MSEC);
}
channel.disconnect();
if (channel.getExitStatus() != 0) {
throw new IOException("Creating directory failed: " + remotePath);
}