Converting working code into a recursive method - java

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

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

How to get the path of a file but without the actual file name

For example C:\Desktop and not C:\Desktop\file.txt.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the split("\") method.
import java.io.*;
public class FilesInfo {
File file = new File("C:\\Users\\CCKS\\Desktop\\1");
public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";
for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}
if(path.equals("")){
return;
} else {
viewFiles();
}
}
public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}
}
}
Like this,
File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();
File file = new File( "C:/testDir/test1.txt" );
String justPath = file.getParent();

Java Gui Text files Output

try {
String hour = (String) comboBox.getSelectedItem();
String filename = fileName.getText();
String date = ((JTextField)dateChooser.getDateEditor().getUiComponent()).getText();
String text = txtKeyword.getText();
String newline = "\n";
String directory = Directory.getText();
File path = new File(directory);
File[] faFiles = path.listFiles();
for(File file: faFiles){
**if(file.getName().contains(filename + "-" + date + "[" + hour + "]") == true == true || file.getName().contains(filename + "-" + date) || file.getName().contains(filename)){**
String line = null;
Reader reader = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
if(line.contains(text)){
jTextArea1.append(line + newline);
btnClear.setEnabled(true);
btnExport.setEnabled(true);
}
}
br.close();
}
}
}
catch(Exception e){
}
Here is my question. I'm trying to use input and loop method to search for a file. The above code works but my problem is lets say I try to find 2 different text files
1. billing-20140527[09].txt has
a)XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)XGMS,2034-05-27 30:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
2. billing-20140527[10].txt has
a)XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b)HELO
**I try to find the number 1 in both text files, if lets say I input the text file name is
billing, I can find the number 1 in both text file and output them:**
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
b) XCGS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.
**However, if I specify the text file name: billing-20140527[09].txt and find the number 1 inside the text file, it will only output:
a) XGMS,2014-05-27 10:08:04,122,PLAYER_VERIFY,VERIFY to LBA,0x580000,0xC0000,253040.**
Can anyone help me with this? Guide or help?
I would work with the BufferedReader. Because it reads a whole line. And then you can split the line by a delimiter (lets say a space " " ). In your case I would write a split-method which receives a String and search for the regex you want.
private void doSearch(File f2) throws IOException,
fileHandler.FileException {
File[] children = f2.listFiles();
if (children != null && searching)
for (int i = 0; i < children.length; i++) {
if (g.isReady()) {
g.setReady(false);
if (!searching) {
g.setReady(true);
break;
} else if (isDirectory(children[i])) {
g.getActualDirectoryInhalt().setText(children[i].getPath()
.substring(g.root.getText().length()));
counterDirectories++;
doSearch(children[i]);
} else if (advancedSearch && !filterSpecified(children[i])) {
raiseCounterForDirectorySize(children[i]);
continue;
} else if (checkFile(children[i])) {
counterFiles++;
searchThroughFile(children[i], this.regex);
raiseCounterForDirectorySize(children[i]);
} else {
g.getTextAreaUnreachable().setText(
g.getTextAreaUnreachable().getText() + f2
+ "\n");
raiseCounterForDirectorySize(children[i]);
}
} else {
doSearch(children[i]);
}
g.setReady(true);
}
}
And here's the other method:
public static void searchThroughFile(File f2, String regex) throws IOException,
fileHandler.FileException {
try {
InputStream is = new BufferedInputStream(new FileInputStream(f2));
String mimeType = URLConnection.guessContentTypeFromStream(is);
ArrayList<String> linesFromFile = fileHandler.FileReaderer
.readFileIntoStringArrayList(f2);
String line = null;
if (f2.getAbsolutePath().contains(regex)) {
g.getTextAreaAdvanced()
.setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + "\n");
}
if (linesFromFile.size() != 0) {
for (int i = 0; i < linesFromFile.size(); i++) {
line = linesFromFile.get(i);
Pattern MY_Pattern = Pattern.compile(regex);
Matcher m = MY_Pattern.matcher(line);
if (!searching) {
break;
}
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
while (m.find() && searching) {
counterFoundPattern++;
g.getFoundFilesInhalt().setText(counterFoundPattern + "");
if (mimeType != null) {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + mimeType + " " + i+1 + "\n");
} else {
g.getTextAreaAdvanced().setText(
g.getTextAreaAdvanced().getText()
+ f2.getPath() + " " + m.group()
+ " " + i+1 + "\n");
}
}
g.setReady(true);
}
}
} catch (IOException e) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTabpane().setForegroundAt(2, Color.RED);
g.getTextAreaException().setText(
g.getTextAreaException().getText() + e + "\n");
g.setReady(true);
} catch (OutOfMemoryError oute) {
MarkOne: if (!g.isReady()) {
break MarkOne;
} else {
g.setReady(false);
}
g.getTextAreaException().setText(
g.getTextAreaException().getText() + "\n"
+ "Fatal Error encured! The File will be skipped!"
+ "\n" + f2.getAbsolutePath());
g.getTabpane().setSelectedIndex(2);
g.setReady(true);
return;
}
}

File last modified time and current time

-I am not using java 8 (Date+Time API...)-I am using Java SE 7
What I am trying to accomplish here is get the last modified time of the directories inside a parent directory in miliseconds , get the current time of the system in miliseconds and then compare them (and delete if...)
This does not seem to work though..
Code:
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = MyParentDirectory.listFiles();
for(File f : subf){
if(f.isDirectory()){
if((Calendar.getInstance().get(Calendar.MILLISECOND) - (f.lastModified() + 1000)) > sec){//The comparison
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length +" folders" + "\n");
}
It look like, there is some problem with File#lastModified() on my Windows, perhaps it is same for you. Try this:
private long getSecondsFromModification(File f) throws IOException {
Path attribPath = f.toPath();
BasicFileAttributes basicAttribs
= Files.readAttributes(attribPath, BasicFileAttributes.class);
return (System.currentTimeMillis()
- basicAttribs.lastModifiedTime().to(TimeUnit.MILLISECONDS))
/ 1000;
}
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = myParentDirectory.listFiles();
for (File f : subf) {
if (f.isDirectory()) {
try {
if (getSecondsFromModification(f) > sec) {
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
} catch (IOException ex) {
System.out.println("Unable to access file " + f.getName() + " informtaion");
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length + " folders" + "\n");
}

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