Recursive method for reading files not working - java

I have this method here, I want to look in a folder recursively to count files that startsWith "D".
It is showing me the StackOverflowError.
public void CountThem() throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()){
CountThem();
}else{
if(f.getName().startsWith("D")){
count++;
}
}
}
}

It's because when a File is a directory, you're starting over your function, that makes an infinite loop. You would have to define the function, that takes a File as a parameter:
public int countThem(File file) throws FileNotFoundException, IOException{
int count = 0;
File []files = file.listFiles();
for(File f : files){
if(f.isDirectory()) {
count += countThem(f);
} else {
if(f.getName().startsWith("D")) {
count++;
}
}
}
return count;
}
P.S.: In java it's a standard to start method names lowercase.
Edit:
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(file);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU(new File("C:/Users/Admin/Desktop/dreniii.txt"));
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

This is the full code
public class Fajlla {
File folder;
FileReader fr;
BufferedReader br;
PrintWriter pw;
public Fajlla(String fld)throws IOException{
folder = new File(fld);
if(!folder.isDirectory()){
throw new IOException("Nuk eshte folder");
}
pw = new PrintWriter(new File("C:/Users/Admin/Desktop/dreniii.txt"));
}
public int callItOUU() throws IOException{
return this.countThem(folder);
}
public int countThem(File folder){
int count = 0;
File [] files = folder.listFiles();
for (File file : files) {
if(file.isDirectory()){
count+=countThem(folder);
}if(file.isFile() && file.canRead()){
count++;
}
}
return count;
}
public static void main(String[] args) {
try {
Fajlla f = new Fajlla("C:/Users/Admin/Desktop/New folder");
int count = f.callItOUU();
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Fajlla.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Related

Java: My ArrayList empties itself as soon as I empty the text file from which the ArrayList gets its contents

I´m writing my own library in java, where you can save variables very simple. But I have a problem in changing the values of the variables. The ArrayList empties itself as soon as the txt file is empty.
My Code:
public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}
Here my SaveGameReader class:
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
And my SaveGameFile class:
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
So, when I call the setValueOf() methode the ArrayList is empty and in the txt file there´s just the first variable + value. Hier´s my data structure:
Name=Testperson
Age=40
Phone=1234
Money=1000
What´s the problem with my code?
In your SaveGameReader.read() method you have result.clear(); which clears ArrayList. And you do it even before opening the file. So basically before every read from file operation you are cleaning up existing state and reread from file. If file is empty then you finish with empty list

Instead of renaming my file just duplicating

I have a program that should process the files in the directory and if the file size is more than 50 bytes delete it. Otherwise, if the file size is less then 50 bytes program should rename the args[1] file to the allFilesContent.txt(same directory), and write all the files to this file, separated by "n" (110 ASCII code). But instead the program just creates another file and writes to the very first args[1] file. What's the problem?
public class Solution
{
public static void main(String [] args) throws IOException
{
File path = new File(args[0]);
File resultFileAbsolutePath = new File(args[1]);
ArrayList<File> allFiles = new ArrayList<>();
boolean isRenamed = false;
for(File file : path.listFiles())
{
if(file.length() > 50)
{
FileUtils.deleteFile(file);
}
else if(file.length() <= 50)
{
if(!isRenamed)
{
FileUtils.renameFile(resultFileAbsolutePath, new File(resultFileAbsolutePath.getParent()+"\\allFilesContent.txt"));
isRenamed = true;
}
if(!file.getName().equals(resultFileAbsolutePath.getName()))
{
allFiles.add(file);
}
}
}
Collections.sort(allFiles, new Comparator<File>()
{
#Override
public int compare(File o1, File o2)
{
return o1.getName().compareTo(o2.getName());
}
});
FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);
for (File file : allFiles)
{
try(FileInputStream fileInputStream = new FileInputStream(file))
{
if(allFiles.indexOf(file) != 0) fileOutputStream.write(110);
int data;
while(fileInputStream.available() > 0)
{
data = fileInputStream.read();
fileOutputStream.write(data);
}
}
}
fileOutputStream.close();
}
public static void deleteFile(File file)
{
if (!file.delete())
{
System.out.println("Can not delete file with name " + file.getName());
}
}
}
And FileUtils class
import java.io.File;
public class FileUtils
{
public static void deleteFile(File file)
{
if (!file.delete())
{
System.out.println("Can not delete file with name " + file.getName());
}
}
public static void renameFile(File source, File destination)
{
if (!source.renameTo(destination))
{
System.out.println("Can not rename file with name " + source.getName());
}
}
}
You have following statement: "FileOutputStream fileOutputStream = new FileOutputStream(resultFileAbsolutePath, true);"
Instead of "true" put "false". It should work.

Mapping name from .txt to a folder in java

I have a folder called attachment which contains 5 .gif images and i have a att.txt which contains name for this .gif images, Now i need to rename these images with the name present in att.txt.
Below is the code i tried.Please help
public static void main(String[] args) throws java.lang.Exception {
java.io.BufferedReader br = new java.io.BufferedReader(new FileReader("D:\\template_export\\template\\attachments"));
String sCurrentLine="";
while ((sCurrentLine = br.readLine()) != null) {
sCurrentLine= sCurrentLine.replaceAll("txt", "gif");
String[] s = sCurrentLine.split(",");
for(int i=0;i<s.length;i++){
new File("D:\\template_export\\template\\attachment_new"+s[i]).mkdirs();
System.out.println("Folder Created");
}
}
}
Try this:
public class Tst {
public static void main(String[] args) {
File orgDirectory = new File("attachements");// replace this filename
// with the path to the folder
// that contains the original images
String fileContent = "";
try (BufferedReader br = new BufferedReader(new FileReader(new File(orgDirectory, "attachements.txt")))) {
for (String line; (line = br.readLine()) != null;) {
fileContent += line;
}
} catch (Exception e) {
e.printStackTrace();
}
String[] newLocations = fileContent.split(" ");
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
File destinationFolder = new File("processed");
int max = Math.min(orgFiles.length, newLocations.length);
for (int i = 0; i < max; i++) {
String newLocation = newLocations[i];
int lastIndex = newLocation.lastIndexOf("/");
if (lastIndex == -1) {
continue;
}
String newDirName = newLocation.substring(0, lastIndex);
String newName = newLocation.substring(lastIndex);
File newDir = new File(destinationFolder, newDirName);
if (!newDir.exists()) {
newDir.mkdir();
}
try {
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It probably won't work since your description isn't that clear but I hope you get the idea and you understand how this task can be done. The important parts are:
File[] orgFiles = orgDirectory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getPath().endsWith(".gif");
}
});
Which creates a File array which contains all the "gif" files in the source directory.
And:
Files.move(orgFiles[i].toPath(), new File(newDir, newName).toPath(), StandardCopyOption.REPLACE_EXISTING);
Which mover the original image to the new directory and sets its name to the one retrieved from the "attachements.txt" file.

How to Convert List of Folders and SubFolder into JSOn FOrmat

i want to populate Folder Name With Sub Folder name on KendoDrop Down . so i want to Convert Folder Directory in JSOn Format How can i Do That ?
public class FolderPath {
public static void main(String[] args) throws IOException {
File currentDir = new File("Folder URL "); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
sb1 = sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
String str = file.getCanonicalPath();
displayDirectoryContents(file);
} else {
}
}
sb1.deleteCharAt(sb1.length() - 1);
sb1 = sb1.append("]");
System.out.println("s2==>" + sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here i am Not Getting Full Directroy into JSOn Please Help
You are creating a StringBuilder object on each iteration. That's why your concatenation does not work.
Consider the contents of you C:\test is composed of 3 directories:
c:\test
|
+--css
| +--less
+--js
The code below, returns:
[{"JSONKEY":"C:\test\css"},
{"JSONKEY":"C:\test\css\less"},
{"JSONKEY":"C:\test\js"}]
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FolderPath {
private static FileFilter onlyDirectories = new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
};
public static void main(String[] args) {
File currentDir = new File("C:\\test"); // current directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
StringBuilder sb1 = new StringBuilder("[");
doDisplayDirectoryContents(dir, sb1);
if (sb1.length() > 1) {
sb1.deleteCharAt(sb1.length() - 1);
}
sb1.append("]");
System.out.println(sb1);
}
private static void doDisplayDirectoryContents(File dir, StringBuilder sb1) {
File[] files = dir.listFiles(onlyDirectories);
if (files != null) {
for (File file : files) {
try {
sb1.append("{\"JSONKEY\":\"" + file.getCanonicalPath() + "\"},");
doDisplayDirectoryContents(file, sb1);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public List<Object> getDirectoryContents(String path) throws IOException {
File directory = new File(path);
File[] files;
enter code here FileFilter fileFilter = file -> file.isDirectory() || file.isFile();
files = directory.listFiles(fileFilter);
List<Object> directoryContent = new ArrayList<>();
if(files != null) {
for (int i = 0; i < files.length; i++) {
File filename = files[i];
String folderPath[] =filename.toString().split("/");
if(files[i].isDirectory()) {
Folder folder = new Folder();
folder.setName(folderPath[folderPath.length - 1]);
folder.setType("folder");
folder.setChildren(mapper.readTree(mapper.writeValueAsString(getDirectoryContents(path + "/" + folder.getName()))));
directoryContent.add(folder);
}
else{
Files file = new Files();
file.setName(folderPath[folderPath.length - 1]);
file.setType("file");
directoryContent.add(file);
}
}
}
return directoryContent;
}
public class Files {
private String name;
private String type = "file";
}
public class Folder {
private String name;
private String type = "folder";
private JsonNode children;
}

Copying children files of a source to a destination in Java

I'm trying to make a program that copies a directory's children, and I can't label all the specific names because they vary throughout each folder. Here's the code I have, but if the source is "C:\src" and the output is "C:\dst" it'll create the folder "C:\dst\src(children files)", but I want to make "C:\dst(children files)". Can anyone help?
public static void copy(File source, File destination) throws IOException {
if (source == null) {
throw new NullPointerException("Null Source");
}
if (destination == null) {
throw new NullPointerException("Null Destination");
}
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
}
//converts to location
public static void copyDirectory(File source, File destination) throws IOException {
copyDirectory(source, destination, null);
}
public static void copyDirectory(File source, File destination, FileFilter filter) throws IOException {
File nextDirectory = new File(destination, source.getName());
if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {// create the directory if necessary...
Object[] filler = {nextDirectory.getAbsolutePath()};
String message = "Dir Copy Failed";
throw new IOException(message);
}
File[] files = source.listFiles();
for (int n = 0; n < files.length; ++n) {// and then all the items below the directory...
if (filter == null || filter.accept(files[n])) {
if (files[n].isDirectory()) {
copyDirectory(files[n], nextDirectory, filter);
} else {
copyFile(files[n], nextDirectory);
}
}
}
}
public static void copyFile(File source, File destination) throws IOException {
// what we really want to do is create a file with the same name in that dir
if (destination.isDirectory()) {
destination = new File(destination, source.getName());
}
FileInputStream input = new FileInputStream(source);
copyFile(input, destination);
}
public static void copyFile(InputStream input, File destination) throws IOException {
OutputStream output = null;
try {
output = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int bytesRead = input.read(buffer);
while (bytesRead >= 0) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} catch (Exception e) {
//
} finally {
input.close();
output.close();
}
input = null;
output = null;
}
Replace
if (source.isDirectory()) {
copyDirectory(source, destination);
} else {
copyFile(source, destination);
}
By
if (source.isDirectory()) {
for (File child : source.listFiles()) {
if (child.isDirectory()) {
copyDirectory(child, destination);
} else {
copyFile(child, destination);
}
}
} else {
copyFile(source, destination);
}
use getParentFile() to get the parent directory:
if (source.isDirectory()) {
copyDirectory(source, destination.getParentFile());
} else {
copyFile(source, destination.getParentFile());
}
You can do everything here in one line using commons-io library :
FileUtils.copyDirectory(src, dest);
see :
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#copyDirectory%28java.io.File,%20java.io.File%29
jar file : http://mvnrepository.com/artifact/commons-io/commons-io/2.4
Try this one. copying whole files in a folder from source to destination.
import java.io.*;
public class copydir
{
public static void main(String args[])
{
File srcFolder = new File("E://Paresh/programs/test");
File destFolder = new File("D://paresh");
if(!srcFolder.exists())
{
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}
else{
try{
copyDirectory(srcFolder,destFolder);
}
catch(IOException e)
{
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyDirectory(File src , File target) throws IOException
{
if (src.isDirectory())
{
if (!target.exists())
{
target.mkdir();
}
String[] children = src.list();
for (int i=0; i<children.length; i++)
{
copyDirectory(new File(src, children[i]),new File(target, children[i]));
}
}
// if Directory exists then only files copy
else
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(target);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}

Categories

Resources