Java - How to list content of a directory? - java

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

Related

reading folder directory content on android java processing

There are a few questions on stack which ask exactly this and yet none of the answers seem to resolve the issue in any way. Please note I am using the processing environment to code, which uses java, but with a wrapper. All java code works natively though.
Code is running on android 10 huawei mate 20 emui 10.
Here is my code. Only the first for loop returns any values, returning "emulated", "sdcard0", and "self", however the subsequent folders return null with the same functions. Permissions have been set in the manifest and in the pde app.
import android.os.Environment;
import android.os.Build ;
import android.app.Activity;
import android.content.Context;
Permission rStorage,wStorage;
void setup(){
rStorage = new Permission(this,"READ_EXTERNAL_STORAGE");
rStorage = new Permission(this,"WRITE_EXTERNAL_STORAGE");
//String path = Environment.getExternalStorageDirectory("storage/").toString();
//println("Files", "Path: " + path);
File directory = new File("storage/");
File[] files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files",null);
directory = new File("storage/emulated");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files emulated",null);
directory = new File("storage/sdcard0");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files sdcard0",null);
directory = new File("storage/self/");
files = directory.listFiles();
if(files!=null){
println("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
println("Files", "FileName:" + files[i].getName());
}
}else println("Files self",null);
};
void draw(){
};
my permission class
public class Permission{
PApplet parent;
public boolean requestedPortraitImage = false;
public Permission(PApplet pParent,String permissionName) {
parent = pParent;
parent.requestPermission("android.permission."+permissionName, "onPermissionResult", this);
println(permissionName);
};
public void onPermissionResult(boolean granted) {
if (!granted) {
PApplet.println("User did not grant camera permission. Camera is disabled.");
}
};
};

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

Reading all files in a path and checking on them 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);
}

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

How to make universal image loader get image from sd card dynamically

i get an example from here
https://github.com/nostra13/Android-Universal-Image-Loader
In the Constants.java is for the image source link. The thing that i want is scan the specific folder in sdcard, then get all image url in dynamic.
Not one by one type the image url.
Not this type one by one. ---> "file:///sdcard/Universal Image Loader ##&=+-_.,!()~'%20.png"
Here is my code. But it can't work. Any solution about this? Thanks.
public class Constants {
private String[] mFileStrings;
private File[] listFile;
static List<String> test = new ArrayList<String>();
public void getFromSdcard()
{
System.out.println("testing here can");
File file= new File(android.os.Environment.getExternalStorageDirectory(),"file:///sdcard/bluetooth/"); //sdcard/bluetooth
if (file.isDirectory())//if files is directory
{
listFile = file.listFiles();
mFileStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
mFileStrings[i] = listFile[i].getAbsolutePath();//mFileStrings with uri of images
test.add(listFile[i].getAbsolutePath());
}
}
}
static String simpleArray = test.toString();
//String img = mFileStrings.toString();
public static final String[] IMAGES = new String[] {simpleArray};
private Constants() {
}
To get image from sdcard, use following code.
String fileName= listFile[i];
fileName = fileName.replace(':', '/');
fileName = fileName.replace('/', '_');
String loadURL="file://"+Environment.getExternalStorageDirectory()+"/"+folder+"/"+fileName;
Now, you have absolute path of your image in "loadURL".
if (file.isDirectory())//if files is directory
{
listFile = file.listFiles();
mFileStrings = new String[listFile.length];
for (int i = 0; i < listFile.length; i++)
{
String fileName=listFile[i];
fileName = fileName.replace(':', '/');
fileName = fileName.replace('/', '_');
String loadURL="file://"+Environment.getExternalStorageDirectory()+"/"+folder+"/"+fileName;
test.add(loadURL);
}
}

Categories

Resources