Finding all the files in my computer using JAVA - java

This is my code for counting all the files in my comp, the code has not stopped running and there are over 2000000 files, is this normal, or is the code in an infinite loop. THanks for all the help :)
import java.io.*;
import java.util.*;
//got the framework from this link: stackoverflow.com/questions/3154488
public class RFF {
public static void main(String [] args) {
File[] files = new File("/Users").listFiles();
showFiles(files);
System.out.println(size);
}
static File file1 = new File ("/Users/varun/Desktop/a.pdf");
static double size = file1.length();
static int i = 0;
public static void showFiles(File[] files) {
try {
for (File file: files) {
if (file.isDirectory()) {
if (file.isFile() == true)
i++;
else
i = i;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " +file.length() + " >>> FileName: " + file.getName() );
showFiles(file.listFiles()); // Calls same method again.
} else {
i++;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " + file.length() + " >>> FileName: " + file.getName() );
}
}
} catch (NullPointerException e) {
System.out.println ("Exception thrown :" + e);
}
}
}

It is highly likely that your users directory contains a shortcut (aka symbolic link) to a folder higher in the path, your code will follow these to get to files it has already counted this will lead to an infinite link.
E.g.
-Users
- Test
-ShortCutToUsers
See this stackoverflow question for more details of determining symbolic links:
Java 1.6 - determine symbolic links
If you're on java 7+ you can determine symbolic links as follows:
Files.isSymbolicLink(path)

Related

Java how to read files recursive

I want to read all files recursive inside a given path and show the path and Byte size in the output of every single File.
public class ReadFilesInPathRecursion {
public void listFiles (String startDir) {
File dir = new File(startDir);
File[] files = dir.listFiles();
if (files!=null && files.length >= 0) {
for(File file : files) {
if(file.isDirectory()) {
listFiles(file.getAbsolutePath()); // Recursion (absolute)
} else {
System.out.println(file.getName() + " (size in bytes: " + file.length() + ") " + "(path: " + file.getAbsoluteFile() + ")");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReadFilesInPathRecursion test = new ReadFilesInPathRecursion();
String startDir = sc.next();
test.listFiles(startDir);
}

PrintStream not creating a file?

I get an error at line 58 which says the file isn't found, but shouldn't the PrintStream have created the file? (Note: No file is created at all.)
Thanks!
WhyDoINeedToAddMoreDetailIAlreadySaidWhatINeedToSay
import java.io.*;
import java.util.*;
import java.text.*;
public class DownloadsFolderCleanup {
public static String directory = "C:\\Users\\User\\Downloads";
public static void main(String[] args) throws FileNotFoundException {
File[] files = (new File(directory)).listFiles();
if (files.length - 1 == 0) {
System.out.println("Downloads folder is already empty!");
}
else {
ArrayList<File> markedFiles = new ArrayList<File>();
int numInstallers = 0, numIncompleteDownloads = 0;
for (File file : files) {
String fileName = file.getName();
if (fileName.substring(fileName.length() - 4,fileName.length()).equals(".exe")) {
if (fileName.toLowerCase().contains("install") || fileName.toLowerCase().contains("setup")) {
markedFiles.add(file);
numInstallers++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Installer");
}
}
if (fileName.length() > 22) {
if (fileName.substring(0,11).equals("Unconfirmed") && fileName.substring(fileName.length() - 11, fileName.length()).equals(".crdownload")) {
markedFiles.add(file);
numIncompleteDownloads++;
System.out.println('"' + fileName + '"' + " marked for deletion. Reason: Incomplete download");
}
}
}
System.out.println("- - - - - - - - - - - - - - - - - - - -");
System.out.println("Total # of files scanned: " + (files.length - 1));
System.out.println("Total # of junk files found: " + markedFiles.size());
System.out.println("Installers found: " + numInstallers);
System.out.println("Incomplete download files found: " + numIncompleteDownloads);
if (markedFiles.size() == 0) {
System.out.println("No junk files were found!");
}
else {
System.out.print("Please confirm removal of all identified files. CANNOT BE UNDONE! Y/N: ");
Scanner input = new Scanner(System.in);
if (input.nextLine().equalsIgnoreCase("Y")) {
System.out.println("All marked files will be permanently deleted in 5 seconds.");
for (int c = 4; c > 0; c--) {
sleep1second();
System.out.println(c + "...");
}
sleep1second();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
Date date = new Date();
PrintStream log = new PrintStream(new File(dateFormat.format(date) + " Download Folder Cleanup Log.txt"));
for (File file : markedFiles) {
System.out.println('"' + file.getName() + '"' + " deleted.");
file.delete();
log.println(file.getName());
}
log.close();
}
}
}
System.out.println();
System.out.println("Cleanup process complete!");
}
public static void sleep1second() {
try {
Thread.sleep(1000);
}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
I'm guessing since your DateFormat "MM/dd/yyyy HH:mm" contains "/" (slashes), that path is invalid and since you're making a file at a path that contains dateFormat.format(date), the file can't be made.
In Windows the following are forbidden characters:
* . " / \ [ ] : ; | = ,

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());
}

Converting working code into a recursive method

Hi guys I needed to create a method to display current directory, files, subdirectories and the files of those subdirectories given a file the user has to choose. I accomplished the task and the fallowing code is printing the appropriated output. It is printing from the f.getParentFile() down, that is what want. Now I want to use recursion instead. I am trying to learn the concept of recursion. I know you need a base case and then your inductive step, but when I try to modify my code into recursive I get an infinite loop when it hits the first subdirectory. Any feedback will be appreciated.
NON-Recursive Working code
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
File[] listFiles = list[i].getAbsoluteFile().listFiles();
for (int j = 0; j < listFiles.length; j++)
{
System.out.println("\t\tSubdirectory files: " + listFiles[j].getName() + "\tsize :" + (listFiles[j].length()/1024) + "KB" );
}
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
Attempting Recursion
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
listFiles(list[i].getAbsoluteFile());
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
It is really really simple :)
public static void main(String[] args) {
filesInFolder("./");
}
public static void filesInFolder(String filename) {
File dir = new File(filename);
for (File child : dir.listFiles()) {
System.out.println(child.getAbsolutePath());
if (child.isDirectory()){
filesInFolder(child.getAbsolutePath());
}
}
}

Transfer folder and subfolders using ChannelSftp in JSch?

I want to transfer a folder and a subfolder using JSch ChannelSftp. I can successfully transfer files using channelsftp.put(src, dest) command but this does not work for folders (at least I could not make it work). So can someone please explain how can I transfer folders and subfolders using ChannelSftp?
To work with multilevel folder structures in jsch you:
enter them;
list their contents;
do smth with every found item;
repeat 1, 2 & 3 if subfolder is found.
DOWNLOAD dirs method inside your JSCH class:
public void downloadDir(String sourcePath, String destPath) throws SftpException { // With subfolders and all files.
// Create local folders if absent.
try {
new File(destPath).mkdirs();
} catch (Exception e) {
System.out.println("Error at : " + destPath);
}
sftpChannel.lcd(destPath);
// Copy remote folders one by one.
lsFolderCopy(sourcePath, destPath); // Separated because loops itself inside for subfolders.
}
private void lsFolderCopy(String sourcePath, String destPath) throws SftpException { // List source (remote, sftp) directory and create a local copy of it - method for every single directory.
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(sourcePath); // List source directory structure.
for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
if (!(new File(destPath + "/" + oListItem.getFilename())).exists() || (oListItem.getAttrs().getMTime() > Long.valueOf(new File(destPath + "/" + oListItem.getFilename()).lastModified() / (long) 1000).intValue())) { // Download only if changed later.
new File(destPath + "/" + oListItem.getFilename());
sftpChannel.get(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Grab file from source ([source filename], [destination filename]).
}
} else if (!(".".equals(oListItem.getFilename()) || "..".equals(oListItem.getFilename()))) {
new File(destPath + "/" + oListItem.getFilename()).mkdirs(); // Empty folder copy.
lsFolderCopy(sourcePath + "/" + oListItem.getFilename(), destPath + "/" + oListItem.getFilename()); // Enter found folder on server to read its contents and create locally.
}
}
}
REMOVE dirs method inside your JSCH class:
try {
sftpChannel.cd(dir);
Vector<ChannelSftp.LsEntry> list = sftpChannel.ls(dir); // List source directory structure.
for (ChannelSftp.LsEntry oListItem : list) { // Iterate objects in the list to get file/folder names.
if (!oListItem.getAttrs().isDir()) { // If it is a file (not a directory).
sftpChannel.rm(dir + "/" + oListItem.getFilename()); // Remove file.
} else if (!(".".equals(oListItem.getFilename()) || "..".equals(oListItem.getFilename()))) { // If it is a subdir.
try {
sftpChannel.rmdir(dir + "/" + oListItem.getFilename()); // Try removing subdir.
} catch (Exception e) { // If subdir is not empty and error occurs.
lsFolderRemove(dir + "/" + oListItem.getFilename()); // Do lsFolderRemove on this subdir to enter it and clear its contents.
}
}
}
sftpChannel.rmdir(dir); // Finally remove the required dir.
} catch (SftpException sftpException) {
System.out.println("Removing " + dir + " failed. It may be already deleted.");
}
CALL these methods from outside like:
MyJSCHClass sftp = new MyJSCHClass();
sftp.removeDir("/mypublic/myfolders");
sftp.disconnect(); // Disconnecting is obligatory - otherwise changes on server can be discarded (e.g. loaded folder disappears).
Above code(by zon) works for download as per my understanding.I need to upload to a remote server.I wrote below code to achieve the same.Please try and comment if any issue(it ignores files starting with ".")
private static void lsFolderCopy(String sourcePath, String destPath,
ChannelSftp sftpChannel) throws SftpException, FileNotFoundException {
File localFile = new File(sourcePath);
if(localFile.isFile())
{
//copy if it is a file
sftpChannel.cd(destPath);
if(!localFile.getName().startsWith("."))
sftpChannel.put(new FileInputStream(localFile), localFile.getName(),ChannelSftp.OVERWRITE);
}
else{
System.out.println("inside else "+localFile.getName());
File[] files = localFile.listFiles();
if(files!=null && files.length > 0 && !localFile.getName().startsWith("."))
{
sftpChannel.cd(destPath);
SftpATTRS attrs = null;
//check if the directory is already existing
try {
attrs = sftpChannel.stat(destPath+"/"+localFile.getName());
} catch (Exception e) {
System.out.println(destPath+"/"+localFile.getName()+" not found");
}
//else create a directory
if (attrs != null) {
System.out.println("Directory exists IsDir="+attrs.isDir());
} else {
System.out.println("Creating dir "+localFile.getName());
sftpChannel.mkdir(localFile.getName());
}
//System.out.println("length " + files.length);
for(int i =0;i<files.length;i++)
{
lsFolderCopy(files[i].getAbsolutePath(),destPath+"/"+localFile.getName(),sftpChannel);
}
}
}
}
From: http://the-project.net16.net/Projekte/projekte/Projekte/Programmieren/sftp-synchronisierung.html
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Vector;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpException;
public class FileMaster {
public boolean FileAction;
public File local;
public String serverDir;
public ChannelSftp channel;
public FileMaster(boolean copyOrDelete, File local, String to, ChannelSftp channel){
this.FileAction = copyOrDelete;
this.local = local;
this.serverDir = to;
this.channel = channel;
}
/*
* If FileAction = true, the File local is copied to the serverDir, else the file is deleted.
*/
public void runMaster() throws FileNotFoundException, SftpException{
if(FileAction){
copy(local, serverDir, channel);
} else {
delete(serverDir, channel);
}
}
/*
* Copies recursive
*/
public static void copy(File localFile, String destPath, ChannelSftp clientChannel) throws SftpException, FileNotFoundException{
if(localFile.isDirectory()){
clientChannel.mkdir(localFile.getName());
GUI.addToConsole("Created Folder: " + localFile.getName() + " in " + destPath);
destPath = destPath + "/" + localFile.getName();
clientChannel.cd(destPath);
for(File file: localFile.listFiles()){
copy(file, destPath, clientChannel);
}
clientChannel.cd(destPath.substring(0, destPath.lastIndexOf('/')));
} else {
GUI.addToConsole("Copying File: " + localFile.getName() + " to " + destPath);
clientChannel.put(new FileInputStream(localFile), localFile.getName(),ChannelSftp.OVERWRITE);
}
}
/*
* File/Folder is deleted, but not recursive
*/
public void delete(String filename, ChannelSftp sFTPchannel) throws SftpException{
if(sFTPchannel.stat(filename).isDir()){
#SuppressWarnings("unchecked")
Vector<LsEntry> fileList = sFTPchannel.ls(filename);
sFTPchannel.cd(filename);
int size = fileList.size();
for(int i = 0; i < size; i++){
if(!fileList.get(i).getFilename().startsWith(".")){
delete(fileList.get(i).getFilename(), sFTPchannel);
}
}
sFTPchannel.cd("..");
sFTPchannel.rmdir(filename);
} else {
sFTPchannel.rm(filename.toString());
}
GUI.addToConsole("Deleted: " + filename + " in " + sFTPchannel.pwd());
}
}

Categories