reading folder directory content on android java processing - java

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

Related

Code for finding the files numbers missing in a folder

I need to identify the file numbers which are missing in a folder.
I have retrieved the files names by using the code below :
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
But now after retrieving i need to find which are the file number which are missing from a file range of 1-1976 both included.
If you need just the filenames, you may use list() method. After you get all the filenames with this method, you can just check the presence of the specified filenames, like:
File parent = ...
String prefix = "xxx_", suffix = ".txt"; // for example
Set<String> files = new HashSet<>(Arrays.asList(parent.list()));
// or, as suggested by #JulienLopez:
String pattern = Pattern.quote(prefix) + "\\d+" + Pattern.quote(suffix);
Set<String> files = new HashSet<>(Arrays.asList(parent.list((dir, file) -> file.matches(pattern))));
for (int i = 1; i <= 1976; ++i) { // actually constant should be used
if (!files.contains(prefix + i + suffix)) {
System.out.format("File #%d doesn't exist%n", i);
}
}
But if you really need to check, that the file is not, for example, the directory, there's one more way to do it, by just creating the Files for every i and checking its existence:
for (int i = 1; i <= 1976; ++i) {
File file = new File(parent, prefix + i + suffix);
if (!file.isFile()) {
System.out.format("File #%d doesn't exist or is directory%n", i);
}
}
I'm not sure your structural of your file name , and what exactly on your mind with "both included". That is my idea,I hope it's a bit help for you.
String FILE_PREFIX= "your_file_prefix"; // Your file prefix. If your file is "logfile_on_20160121_0001" then the prefix is "logfile_on_20160121_"
int RANGE_MIN = 1;
int RANGE_MAX = 1976;
int fileList[] = new int[RANGE_MAX];
int directoryList[] = new int[RANGE_MAX];
// Quote your code with a bit modify from me
File folder = new File(FILE_PATH);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
fileList[seq] = 1;
}
}
// Added ended
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
// Added started
String tempSplitedName[] = listOfFiles[i].split(FILE_PREFIX);
if(tempSplitedName.length==2){
int seq = Integer.parseInt(tempSplitedName[2]);
if(seq>=RANGE_MIN && seq<=RANGE_MAX){
directoryList[seq] = 1;
}
}
// Added ended
}
// Now you count missing files/directory, which is equal 0
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(fileList[i]==0) System.out.println("Missing file No." + i);
}
for (int i=RANGE_MIN; i<=RANGE_MAX; i++){
if(directoryList[i]==0) System.out.println("Missing directory No." + i);
}

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

Prevent Dir deleting

the following code is deleting files and DIRS in a specific folder.
How could I adjust it, so it will delete only the files in the folder but not the dirs inside
code:
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
thanks,
ray.
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (int i = 0; i < listOfFiles.length; i++)
{
if( !listOfFiles[i].isDirectory() ){ // if not a directory...
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
}
}
Make sense? :)
Easy ...
if (!listOfFiles[i].isDirectory()) {
listOfFiles[i].delete();
}
FWIW - your current code will only delete empty subdirectories. According to the javadoc, deleting a directory that is non-empty will fail; i.e. return false.
You have to use File.isDirectory
if(!listOfFiles[i].isDirectory())
{
logger.debug("File name=" + listOfFiles[i].toString() + " is Deleted!");
listOfFiles[i].delete();
}
http://download.oracle.com/javase/6/docs/api/java/io/File.html#isDirectory()
if (!listOfFiles[i].isDirectory()) { listOfFiles[i].delete(); }

when getting drive information using java

i tried the following program
import java.io.*;
class dr
{
public static void main(String args[])
{
try{
File[] roots = File.listRoots();
for (int index = 0; index < roots.length; index++)
{ //Print out each drive/partition
System.out.println(roots[index].toString());
}
}
catch(Exception e)
{
System.out.println("error " +e);
}
}
}
but in my system floppy drive is not connected
and i am getting a message like the following
" The drive is not ready for use;its door may be open,Please check drive A: and make sure that disk is inserted and that the drive door is closed"
then three options are shown cancel,try again,continue
when i try continue,it works
but how i could avoid that msg
What are you trying to do?
My recommendation would be to use FileSystemView.
It's used something like this:
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (File f: roots) {
System.out.println(fsv.getSystemDisplayName(f);
}
package com.littletutorials.fs;
import java.io.*;
import javax.swing.filechooser.*;
public class DriveTypeInfo
{
public static void main(String[] args)
{
System.out.println("File system roots returned byFileSystemView.getFileSystemView():");
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
for (int i = 0; i < roots.length; i++)
{
System.out.println("Root: " + roots[i]);
}
System.out.println("Home directory: " + fsv.getHomeDirectory());
System.out.println("File system roots returned by File.listRoots():");
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++)
{
System.out.println("Drive: " + f[i]);
System.out.println("Display name: " + fsv.getSystemDisplayName(f[i]));
System.out.println("Is drive: " + fsv.isDrive(f[i]));
System.out.println("Is floppy: " + fsv.isFloppyDrive(f[i]));
System.out.println("Readable: " + f[i].canRead());
System.out.println("Writable: " + f[i].canWrite());
System.out.println("Total space: " + f[i].getTotalSpace());
System.out.println("Usable space: " + f[i].getUsableSpace());
}
}
}
reference : http://littletutorials.com/2008/03/10/getting-file-system-details-in-java/
When it comes to Windows, this class WindowsAltFileSystemView proposes an alternative based on FileSystemView
This class is necessary due to an annoying bug on Windows NT where instantiating a JFileChooser with the default FileSystemView will cause a "drive A: not ready" error every time.
I grabbed the Windows FileSystemView impl from the 1.3 SDK and modified it so * as to not use java.io.File.listRoots() to get fileSystem roots.
java.io.File.listRoots() does a SecurityManager.checkRead() which causes the OS to try to access drive A: even when there is no disk, causing an annoying "abort, retry, ignore" popup message every time we instantiate a JFileChooser!
So here, the idea is to extends FileSystemView, replacing the getRoots() method with:
/**
* Returns all root partitians on this system. On Windows, this
* will be the A: through Z: drives.
*/
public File[] getRoots() {
Vector rootsVector = new Vector();
// Create the A: drive whether it is mounted or not
FileSystemRoot floppy = new FileSystemRoot("A" + ":" + "\\");
rootsVector.addElement(floppy);
// Run through all possible mount points and check
// for their existance.
for (char c = 'C'; c <= 'Z'; c++) {
char device[] = {c, ':', '\\'};
String deviceName = new String(device);
File deviceFile = new FileSystemRoot(deviceName);
if (deviceFile != null && deviceFile.exists()) {
rootsVector.addElement(deviceFile);
}
}
File[] roots = new File[rootsVector.size()];
rootsVector.copyInto(roots);
return roots;
}
you can use this;
import java.io.File;
class dr
{
public static void main(String args[])
{
File[] roots=File.listRoots();
for(File root:roots)
{
System.out.println(root.getName());
}
}
}

Categories

Resources