Reading all files in a path and checking on them java - java

I am reading all files in the paths which mentioned in the code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class folderReader {
public static void main(String[] args) {
//Extension > .wav files
File folderWav = new File(
"/home/bassem/Desktop/LatestData3/Nemlar_RMC/nemlar_RMC");
File[] listOfWavs = folderWav.listFiles();
//Extension > .insent
File folderInsent = new File(
"/home/bassem/Desktop/LatestData3/outputInsent");
File[] listOfInsents = folderInsent.listFiles();
//Extension > .ctl
File folderCtl = new File("/home/bassem/Desktop/LatestData3/outputCtl");
File[] listOfCtls = folderCtl.listFiles();
for (File file : listOfWavs) {
for (File file2 : listOfInsents) {
for (File file3 : listOfCtls) {
if (file.isFile() && file2.isFile() && file3.isFile()) {
if ((file.getName().substring(0,
file.getName().length() - 4).equals(file3
.getName().substring(0,
file3.getName().length() - 4)))) {
if ((file2.getName().substring(0,
file2.getName().length() - 7).equals(file3
.getName().substring(0,
file3.getName().length() - 4)))) {
System.out.println(file3.getAbsolutePath());
}
}
}
}
}
}
}
}
After Reading all the files I am checking on their names with using substring to remove (.ctl - .insent - .wav) and if they are equaled I should do some stuff I am trying here to print path to check if the code is working and it prints nothing
I tried to use this and it worked well it printed them all.
for (File file : listOfWavs) {
for (File file2 : listOfInsents) {
if (file.isFile() && file2.isFile()) {
if ((file.getName().substring(0,
file.getName().length() - 4).equals(file2.getName()
.substring(0, file2.getName().length() - 7)))) {
System.out.println(file2.getAbsolutePath());
}
}
}
}
the problem only happens when i am checking on the 3 folders together when I run the code it does nothing just an empty console !

String folder = "/home/bassem/Desktop/LatestData3/";
List<String> insents = readFolderBasenames(folder + "outputInsent", "insent");
List<String> wavs = readFolderBasenames(folder + "Nemlar_RMC/nemlar_RMC", "wav");
List<String> ctls = readFolderBasenames(folder + "outputCtl", "ctl");
insents.retainAll(wavs);
insents.retainAll(ctls);
for(String file : insents) {
System.out.println(folder + file + ".insent");
}
private List<String> readFolderBasenames(String path, String extension) {
File[] arr = new File(path).listFiles());
for(int i=0; i<arr.length; i++) {
arr[i] = arr[i].getName().substring(0, arr[i].getName().length() - extension.length() - 1);
}
return Arrays.asList(arr);
}

Related

Java - Read package and Class name from file

I am trying to read package and class name from file. In the below code fileEntry.getName() is giving me output C:User\mywork\Myproject\target\generated-source\java\demo\Project.java. I want to get only demo.Project as an output. Appreciate suggestion thank you
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
//C:User\mywork\Myproject\target\generated-source\java\demo\Project.java
}
}
}
I suppose you only need to find java class files and you want inner packages declared as package1.package2.demo.Project. You can do some String manipulation to get that output.
public static String FILE_SEPARATOR = System.getProperty("file.separator");
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if (!fileEntry.getName().endsWith(".java")) {
continue;
}
String absolutePath = fileEntry.getAbsolutePath();
String javaPackageSeparator = FILE_SEPARATOR + "java" + FILE_SEPARATOR;
int indexOf = absolutePath.indexOf(javaPackageSeparator);
if (indexOf > -1) {
String javaFilePath = absolutePath.substring(indexOf, absolutePath.length());
String strippedJavaSeparator = javaFilePath.replace(javaPackageSeparator, "");
String[] constructProperPackageName = strippedJavaSeparator.split(Pattern.quote(FILE_SEPARATOR));
String packageName = "";
String className = "";
for (int i = 0; i < constructProperPackageName.length; i++) {
if (i == constructProperPackageName.length - 1) {
className = constructProperPackageName[i].replace(".java", "");
continue;
}
packageName += constructProperPackageName[i] + ".";
}
System.out.println(packageName + className);
}
}
}
}
Produces output as following:
com.company.exception.handler.AbstractExceptionHandler
com.company.exception.handler.IExceptionHandler
com.company.exception.handler.APIRequestExceptionHandler
...
A simple scan across the root / source directory using Files.find will return all java files, and then you can adjust the path to generate package name.
Path srcDir = Path.of("src");
BiPredicate<Path, BasicFileAttributes> dotjava = (p,a) -> a.isRegularFile() && p.getFileName().toString().endsWith(".java");
try(var java = Files.find(srcDir, Integer.MAX_VALUE, dotjava)) {
java.map(p -> srcDir.relativize(p).toString().replaceAll("\\.java$", "").replace(File.separator, "."))
.forEach(System.out::println);
}

how to display the console result in a textarea with java

here is a java program that allows to display the files of each directory
the problem how to display the result in a textarea
private static void
findFilesRecursively(File file, Collection<File> all, final String extension) {
final File[] children = file.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.getName().endsWith(extension) ;
}}
);
if (children != null) {
//Pour chaque fichier recupere, on appelle a nouveau la methode
for (File child : children) {
all.add(child);
findFilesRecursively(child, all, extension);
}
}
}
public static void main(String[] args)
{
//try {
final Collection<File> all = new ArrayList<File>();
// JFileChooser fc = new JFileChooser(".");
// int returnVal = fc.showOpenDialog(null);
findFilesRecursively(new File("c:\\repertoire"), all,"");
//File outputFile = new File("C:\\Users\\21365\\Desktop\\tt.txt");
//FileOutputStream fos = new FileOutputStream(outputFile);
for (int i = 0; i < all.size(); i++) {
for (File file : all) {
if(file.isDirectory()==true){
System.out.println("le repertoire \t"+file.getName()+"\t contien");
}else{
You should not iterate through your list twice - get rid of one of these 2 for loops :
for (int i = 0; i < all.size(); i++) {
for (File file : all) {
Also instead of using System.out.println(…) to print to console, just create a JFrame / JTextArea and use its append(String text) method, eg :
if (file.isDirectory() == true) {
yourTextArea.append("le repertoire \t" + file.getName() + "\t contien");
} else {
yourTextArea.append(file.getName());
}

How to store list of files and folder in list or set using java?

I have return code to retrieve a list of all filepaths within a directory but I'm only getting the contents of the last folder. I have two folders, each has 3 files.
Here is my code:
import java.io.*;
import java.util.*;
class Filedirexts
{
public static void main(String[] args) throws IOException
{
String Dirpath = "E:/Share/tstlpatches";
String fieldirpath ="";
File file = new File(Dirpath);
List<String> strfilelst = new ArrayList<String>();
strfilelst = Filedirexts.getsubdir(file);
System.out.println(strfilelst.size());
for(int i=0;i<strfilelst.size();i++)
{
fieldirpath = strfilelst.get(i);
System.out.println("fieldirpath : "+fieldirpath);
}
}
public static List<String> getsubdir(File file) throws IOException
{
File[] filelist = file.listFiles();
List<String> strfileList = new ArrayList<String>();
System.out.println("filelist" + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+fileeach.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+fileeach.getCanonicalPath());
strfileList = Filedirexts.getsubdir(file);
strfileList.add(file.getCanonicalPath().toString());
}
}
}
return strfileList;
}
}
This is my folder structure:
MainPath E:\Share\tstlpatches which is used in code itself
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\graphical
E:\Share\tstlpatches\BE\graphical\data1.txt
E:\Share\tstlpatches\BE\graphical\data2.txt
E:\Share\tstlpatches\BE\graphical\data3.txt
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
I'm only getting
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
If I use the normal method, it works fine, but when I use with the list I'm only getting the constents of the last folder.
What do I need to do to make the code work properly?
Your recursive method is incorrectly creating a new ArrayList<String> in each call and returning this new ArrayList in each invocation. This is why you are only seeing the contents of the last call.
Here's how to fix this:
1) Change the getsubdir to be void and pass in the List as a parameter.
public static void getsubdir(File file, List<String> strfileList) throws IOException
{
File[] filelist = file.listFiles();
System.out.println("filelist " + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+file.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+file.getCanonicalPath());
// Note: Since you want the directory first in the list,
// add it before the recursive call
strfileList.add(file.getCanonicalPath().toString());
Filedirexts.getsubdir(file, strfileList);
}
}
}
}
2) Change the way you call it from main:
Instead of:
strfilelst = Filedirexts.getsubdir(file);
Just use:
Filedirexts.getsubdir(file, strfilelst);

How to rename file java ?

I'm trying to rename files in a folder. But instead all of them get deleted
File thisFolder = new File("C:\\ . . . ");
File [] filesArray = thisFolder.listFiles();
int filesArrayLength = filesArray.length;
if (filesArray != null) {
for (int i = 0; i < filesArrayLength; i++) {
filesArray[i].renameTo(new File("test" + i + ".pdf"));
}
}
What am i doing wrong ? Why do all of the files get deleted instead of renamed
As #Pshemo pointed out you might be moving the file to the current directory. Try doing this instead. This will tell it to create the file under the given parent directory:
filesArray[i].renameTo(new File(thisFolder, "test" + i + ".pdf"));//thisFolder is your parent directory
String strFilePath= "C:/Users/";
public void renameFile(String strOldFileName, String strNewFileName) {
File oldName = new File(strFilePath + "/" + strOldFileName);
File newName = new File(strFilePath + "/" + strNewFileName);
if (oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
Code example for you to rename the List of files in a given directory as below,
Suppose C:\Test\FileToRename isthe folder, the files which are listed under that has been renamed to test1.pdf,test2.pdf... etc..
File folder = new File("\\Test\\FileToRename");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File("c:\\Test\\FileToRename\\"+listOfFiles[i].getName());
f.renameTo(new File("c:\\Test\\FileToRename\\"+"test"+i+".pdf"));
}
}

Java - How to list content of a directory?

I want to display the content of the directory /etc/yum.repos.d in Centos. Usually in this directory is stored information about repositories from which Centos downloads RPM packages.
What is the proper way to display the content of a directory in Java?
Best wishes
import java.io.File;
import java.util.Arrays;
public class Dir {
static int indentLevel = -1;
static void listPath(File path) {
File files[];
indentLevel++;
files = path.listFiles();
Arrays.sort(files);
for (int i = 0, n = files.length; i < n; i++) {
for (int indent = 0; indent < indentLevel; indent++) {
System.out.print(" ");
}
System.out.println(files[i].toString());
if (files[i].isDirectory()) {
listPath(files[i]);
}
}
indentLevel--;
}
public static void main(String args[]) {
listPath(new File("/etc/yum.repos.d"));
}
}
Here is an example :
File directory = new File("/etc/yum.repos.d");
File[] files = directory.listFiles();
File dir = new File("some_directory");
String[] filesAndSubdirs = dir.list();

Categories

Resources