ifFile Does not recognize csv, pl, sh, xml files - java

I'm building an array of a recursive search of a directory. That part works great, but when trying to determine if a file is a file, it only adds .txt files into the array, and skips over files like csv, pl, sh, xml and so on. Is the something I can do to fix this? here is the code I'm working with.
public static ArrayList<Object> listDirectory(String directory) {
Object sbytes;
File dir = new File((String) directory);
File[] firstLevelFiles = dir.listFiles();
ArrayList<Object> array = new ArrayList <Object>();
if (firstLevelFiles != null) {
for (File aFile : firstLevelFiles) {
//if (aFile.isFile()) {
if (! aFile.isDirectory()) {
System.out.println("[" + aFile.getAbsolutePath() + "]");
long bytes = aFile.length();
if (bytes > 1000) {
sbytes = bytes / 1000 + " Kb";
} else if (bytes > 1000000){
sbytes = bytes / 1000000 + " Mb";
} else {
sbytes = bytes + " bytes";
}
Object fileName = aFile.getName();
Object nameAndSize = fileName + " " + sbytes;
array.add(nameAndSize);
} else {
ArrayList<Object> deeperList = listDirectory(aFile.getAbsolutePath());
array.addAll(deeperList);
}
}
}
return array;
}

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 delete file based on name length

I have a list of files with same suffix , the name of files contain date and file type like this : year-month-day_filetype .. except one of them doesn't contain day ( year-month_filetype ) -you can see the picture - .. I need to delete that one doesn't contain day .. please help .. many thanks
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder) {
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles()) {
if (f.getName().contains("CW")) {
f.delete();
}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
So you need a function to check if your string is the format you expect but missing the day. This should do the trick.
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}
Then you'll say something like:
if (f.getName().contains("CW") || missingDay(f.getName())
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder){
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
}else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles())
{
if (f.getName().contains("CW") || missingDay(f.getName())){
f.delete();}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}

Get java.lang.NullPointerException reading size app folder

I want read the size of app folder. I can do it also with system app without problems but the "normal" app folder it gets me problems. I do in this way:
File apk = new File("/data/app");
if (apk.exists()){
float apksize=getFolderSize(apk)/(1024f*1024f);
apk.setText(Html.fromHtml(getResources().getString(R.string.apk)+ " " +"<b>" +String.format("%.2f", apksize)+ " " + "Mb" + "</b>"
));
} else {
apk.setText(devicefragment.this.getResources().getString(R.string.folderapknotfound));
}
and then the method for folder size
public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
if (file.isFile()) {
// System.out.println(file.getName() + " " + file.length());
size += file.length();
} else
size += getFolderSize(file);
}
return size;
}
for every other folders i try it works well.. this one nope. The logcat return:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.myapp.deviceinfo.getFolderSize(devicefragment.java:316)
at com.myapp.deviceinfo.onCreateView(devicefragment.java:179)
...
where line 316 is : size += getFolderSize(file); and line 179 is: float apksize=getFolderSize(apk)/(1024f*1024f);
i don't know why it crashes honestly.. no root needs for this operation.
edit:
i tried:
public static long getFolderSize(File dir) {
long size = 0;
for (File file : dir.listFiles()) {
if (file == null) {
continue;
}
if (file.isFile()) {
// System.out.println(file.getName() + " " + file.length());
size += file.length();
} else
size += getFolderSize(file);
}
return size;
}
but crashes anyway
One (or more) of your File objects named file is null in the loop in getFolderSize. The easiest way to fix this is to ignore objects that are null by adding a null check inside the loop:
for (File file : dir.listFiles()) {
if(file == null) {
continue;
}
...
}
for (File file : dir.listFiles()) {
dir.listFiles() can return null. So better determine first and check for null before use.

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

Categories