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.
Related
please help me this code, I don't know how android manage files & folders
I use a function that get the list of files documents in android storage, but after check each file, that result illegal, exception throw: No such file or directory
**public void doJob() {
Log.d(TAG, "Check01952039847501: " + mListFileInput.size());
// list 27 files input
for (int i = 0; i < mListFileInput.size(); i++) {
File file = new File(mListFileInput.get(i));
Log.d(TAG, "Check010684946823046 = " + file);
// /storage/0F37-7BF9/aliasBook2/Da-Vinci.epub
Log.d(TAG, "Check010684946823046: check file: " + file.exists());
// false
try {
ZipFile zipFile = new ZipFile(file);
} catch (IOException e) {
e.printStackTrace();
// Exception throw "such file or directory android", all files
}
}
}**
Note: To get that mListFileInput list, I use recuisive function this:
**public void recuisiveGetEbook(File directory) {
File[] fileList = directory.listFiles();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
File file = fileList[i];
if (!file.getPath().contains("/Android")
&& !file.getPath().contains("/data")
&& !file.isHidden()) {
// if that is file
if (file.isFile() && file.exists() && file.canRead()) {
if (file.getName().endsWith(".epub")) {
lstResult.add(fileList[i].getPath());
Log.d(TAG, "Check019252357: " + fileList[i].getPath());
}
} // if that is folder
else recuisive1(fileList[i]);
}
}
}
}**
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;
}
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);
}
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;
}
This is my code for counting all the files in my comp, the code has not stopped running and there are over 2000000 files, is this normal, or is the code in an infinite loop. THanks for all the help :)
import java.io.*;
import java.util.*;
//got the framework from this link: stackoverflow.com/questions/3154488
public class RFF {
public static void main(String [] args) {
File[] files = new File("/Users").listFiles();
showFiles(files);
System.out.println(size);
}
static File file1 = new File ("/Users/varun/Desktop/a.pdf");
static double size = file1.length();
static int i = 0;
public static void showFiles(File[] files) {
try {
for (File file: files) {
if (file.isDirectory()) {
if (file.isFile() == true)
i++;
else
i = i;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " +file.length() + " >>> FileName: " + file.getName() );
showFiles(file.listFiles()); // Calls same method again.
} else {
i++;
if (file.length() > size)
size = file.length();
System.out.println("FileCount: " + i + ">>> FileSize: " + file.length() + " >>> FileName: " + file.getName() );
}
}
} catch (NullPointerException e) {
System.out.println ("Exception thrown :" + e);
}
}
}
It is highly likely that your users directory contains a shortcut (aka symbolic link) to a folder higher in the path, your code will follow these to get to files it has already counted this will lead to an infinite link.
E.g.
-Users
- Test
-ShortCutToUsers
See this stackoverflow question for more details of determining symbolic links:
Java 1.6 - determine symbolic links
If you're on java 7+ you can determine symbolic links as follows:
Files.isSymbolicLink(path)