I have a problem getting the size of a file.
I have the following code:
File file = new File(path);
FilenameFilter mediafilefilter = new FilenameFilter(){
private String[] filter = {".txt"};
#Override
public boolean accept(File dir, String filename) {
for(int i= 0;i< filter.length ; i++){
if(filename.indexOf(filter[i]) != -1)return true;
}
return false;
}
};
File[] flies = file.listFiles(mediafilefilter);
if (files != null) {
{
if (files.length > 0)
{
System.out.println("Totol is :" + files.length);
for (int j = 0; j < files.length; j++) //not work
}
}
}
some text file is 0 byte
Like that
list[0].length()/1024
list[0] is the first file in your array
public long getFileSizes(File f) throws Exception{
long s=0;
if (f.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(f);
s= fis.available();
}
return s;
}
Related
I'm making application that find specific file in my storage.
So I put all file list into List.
Root = Environment.getExternalStorageDirectory().getAbsolutePath();
List<String> fileList = new ArrayList<String>();
searchFile(new File(Root));
void searchFile(File directory){
File[] files = directory.listFiles();
try{
if(directory.exists()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].exists()) {
if (files[i].isDirectory()) {
File[] file = files[i].listFiles();
for (int j = 0; j < file.length; j++) {
searchFile(file[j].getPath());
}
} else
fileList.add(files[i].getPath());
}
}
}
} catch(Exception ex){}
}
But My the number of all file is more than 60000.
So When I tried to debug, It worked so slowly.
How can I get All file list in my storage quickly?
Please try the below code.
Root = Environment.getExternalStorageDirectory().getAbsolutePath();
List<String> fileList = new ArrayList<String>();
searchFile(new File(Root));
void searchFile(File directory){
try{
if(directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
if(file.exists()) {
if (file.isDirectory()) {
File[] innerFiles = file.listFiles();
for (File innerFile : innerFiles) {
searchFile(innerile.getPath());
}
} else
fileList.add(file.getPath());
}
}
}
} catch(Exception ex){}
}
This will narrow down your performance issue to a certain level.
i have a Problem with String[] array.I refer about this from Here
& Here
But still, i have not found any solution from the link.
What I want:
I am developing a Custom Camera App.I have a Folder in which I am saving a Captured images.also, i have 1 ImageView. when my App Launched the Image [or Bitmap] of Folder is set into that ImageView (Always set the First image of the folder into ImageView).
Following is my Code.
private void loadImageInImageView() {
Uri[] mUrls;
String[] mFiles = new String[0];
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (mFiles.length >= 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
}
in Above code [when Folder is Empty] :
When i set if (mFiles.length > 0)
it shows me an Error
Error: Attempt to get length of null array
When i set if (mFiles.length >= 0)
Then it shows me same as Above Error.
When i set if (mFiles == null)
it is also not Working because I have initialized String[] in above code.
String[] mFiles = new String[0];
Hence it also not work.
When I have some Images then it working Fine.because it executed the else part.
what should I do?Whenever my Folder is Empty then it Shows me a Toast.otherwise my else code will be executed.
Any help will be Highly appreciated.
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imageList.length = 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
String[] mFiles = new String[imageList.length];
for (int i = 0; i < imageList.length; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
If the function you want works when the size of the imageList is greater than zero, try below code.
private void loadImageInImageView() {
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
File[] imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
// conditional operator [ ? : ]
// value = (experssion) ? value if true : value if false
// ref : https://www.tutorialspoint.com/java/java_basic_operators.htm
int imgLength = imageList == null ? 0 : imageList.length;
if(imgLength > 0)
{
String[] mFiles = new String[imgLength];
Uri[] mUrls = new Uri[imgLength];
//merge for condition
for (int i = 0; i < imgLength; i++) {
mFiles[i] = imageList[i].getAbsolutePath();
mUrls[i] = Uri.parse(mFiles[i]);
imgBtnThumbnail.setImageURI(mUrls[i]);
}
}
else
{
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
}
}
Do not initialize mFiles. Initialize it in the moment when you add some data.
And for checking if it isn't empty use this:
if (mFiles != null && mFiles.length > 0) {
...
}
private void loadImageInImageView() {
Uri[] mUrls;
File[] imageList
File file = new File(android.os.Environment.getExternalStorageDirectory(), "CameraApp/Images");
imageList = file.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")) || (name.endsWith(".mp4")));
}
});
if (imagelist==null && imageList.length == 0) {
Toast.makeText(this, "No Captured Images", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < imageList.length; i++) {
imgBtnThumbnail.setImageURI(Uri.parse(imageList[i].getAbsolutePath()););
}
}
}
try this;
but your image changes continuously because of for loop;
I am able to change file extensions, for example, from ".mp4" to ".xmp4" but instead of changing extension, i simply want to add a "." before a file name for example "mikey.jpg" to ".mikey.jpg". how do i do that?
public static final String[] TARGET_EXTENSIONS = { "mp4", "mp3", "mp55", "other" };
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".x" + ext);
}
listFile[i].renameTo(new File(fPath));
}
}
}
}
here is the full code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (LinearLayout) findViewById(R.id.view);
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
walkdir(dir);
}
public static final String[] TARGET_EXTENSIONS = { "mp4", "mp3", "avi", "other" };
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".x" + ext);
}
listFile[i].renameTo(new File(fPath));
}
}
}
}
}
first you do String fileName = listFile[i].getName(); , which should give you the name, next you do String fullPath = listFile[i].getAbsolutePath(); to get the full path, then you do int indexOfFileNameStart = fullPath.lastIndexOf(fileName) , then you get a string builder instance from fullPath like so StringBuilder sb = new StringBuilder(fullPath); , now you call the insert method on sb sb.insert(indexOfFileNameStart, "."), now sb should have the string you desire, just construct it to string sb.toString()
Ill add this in code
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfFileNameStart = fullPath.lastIndexOf(fileName);
StringBuilder sb = new StringBuilder(fullPath);
sb.insert(indexOfFileNameStart, ".");
String myRequiredFileName = sb.toString();
file.renameTo(new File(myRequiredFileName));
return myRequiredFileName;
}
EDIT
This is how you can use the above method in your code
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
if(fPath.endsWith(ext)) {
putDotBeforeFileName(listFile[i]);
}
}
}
}
}
}
I want to read specific line from file like text.txt then write some string to it. any method to do that on android? I'm still play around with LineNumberReader, but still cant find way to do that.
Thanks.
Why not use a combination of inputstream, bufferedreader, stringbuilder, and an outputstream?
Maybe anybody get the same case like that..
private void Writing() {
// TODO Auto-generated method stub
try {
String[] lines = new String[888];
File internalStorage = Environment.getDataDirectory();
File dir = new File (internalStorage + "/myPde");
File file = new File(dir, "ekfslam.pde");
File file_temp = new File(dir, "ekfslam_temp.txt");
FileWriter fw = new FileWriter(file_temp,true);
BufferedWriter bw = new BufferedWriter(fw);
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
file_temp.createNewFile();
int i = 0;
String Line = "";
while (true) {
Line = lnr.readLine();
if (Line != null) {
lines[i]=Line;
i++;
} else {
break;
}
}
for (int j = 0; j < 50; j+=5) {
lines[95] = lines[95]+"\n\t\t Data "+j;
}
if (file_temp.exists()) {
} else {
file_temp.createNewFile();
}
for (i = 0; i < lines.length; i++){
bw.write(lines[i]);
bw.newLine();
System.out.println(lines[i]);
}
file.delete();
file_temp.renameTo(file);
bw.close();
lnr.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This is any way to delete only .jpg files from folder?
This is my remove method:
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
new File(dir, children[i]).delete();
}
}
How can I remove only .jpg files from folder?
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
String filename = children[i];
if (filename.endsWith(".jpeg") || filename.endsWith(".jpg"))
new File(dir, filename).delete();
}
}
or you prefer the for-each version
if (dir.isDirectory()) {
String[] children = dir.list();
for (String child : children) {
if (child.endsWith(".jpeg") || child.endsWith(".jpeg"))
new File(dir, child).delete();
}
}
Try like this
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
if(children[i].endsWith('.jpg' || children[i].endsWith('.jpeg'))
{
new File(dir, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder");
Then call
walkdir(dir);
public void walkdir(File dir) {
String Patternjpg = ".jpg";
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
if (listFile[i].getName().endsWith(Patternjpg)){
//Do what ever u want
listFile[i].delete();
}
}
}
}
}