Android Filesystem - java

I've been trying to get this working, but I'm stumbling somewhere.
Here is the major source of the whole thing. And the logcat result...some is a bit redundant. I have "startingDirectory" above the onCreate, so I copied and removed the private...
String startingDirectory = Environment.getExternalStorageDirectory().getAbsolutePath();
String directory = startingDirectory;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == false) {
Log.d(TAG, "Media is not mounted.");
} else {
Log.d(TAG, "Loading File Directory.");
Log.d(TAG, "Directory listing for " + directory);
File path = new File(directory);
//File path = new File(directory);
if (path.isDirectory()) {
if (path.canRead()) {
Log.d(TAG, "Readable directory");
} else {
Log.d(TAG, "Non-readable directory");
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Log.d(TAG, "Media is mounted");
} else {
Log.d(TAG, "Media is not mounted");
}
}
} else {
Log.d(TAG, "Is not a directory.");
}
}
And here is the logcat of the whole thing...
07-13 01:13:45.705 4361-4361/? D/MainActivity: Loading File Directory.
07-13 01:13:45.705 4361-4361/? D/MainActivity: Directory listing for /storage/emulated/0
07-13 01:13:45.705 4361-4361/? D/MainActivity: Non-readable directory
07-13 01:13:45.706 4361-4361/? D/MainActivity: Media is mounted
I'm trying to get the directory structure of current directory (staringDirectory) and place into an class...but it doesn't seem to stay from non-readable

This is my permitFileAcess method using setWritable and setReadable method of java.io.File class whenever I modify some file and directory's permission.
Well, I still have got a message but it works for me
public static void permitFileAcess(final File file) {
if (!file.setWritable(true, true)) {
log.e(new Object[] { "Could not set Writable permissions" });
}
if (!file.setReadable(true, true)) {
log.e(new Object[] { "Could not set Readable permissions" });
}
if (!file.setExecutable(true, true)) {
log.e(new Object[] { "Could not set Executable permissions" });
}
}
So, if you want to create a file use it before the operation.
private static boolean createFile(File parent, String fileName, boolean createDir) {
boolean returnValue = false;
if (parent.isDirectory()) {
File newFile = new File(parent.getAbsolutePath(), fileName);
permitFileAcess(newFile);
if (createDir) {
returnValue = newFile.mkdir();
} else {
try {
returnValue = newFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return returnValue;
}
Good luck.

I'm trying to retrieve all of the files and directories in a specific dir. To make a simple file file manager. If I don't SEE the file, I wouldn't know which one to load in.

Related

How do I force mkdir to overwrite existing directory?

I need to have my program create a directory with a specific name, and overwrite any existing directory with that name. Currently, my program doesn't seem to be able to overwrite the directory. Is there any way of forcing the overwrite?
private boolean makeDirectory(){
File file = new File(TEMP_DIR_PATH + "/" + clipName);
if (file.mkdir()) {
return true;
}
else {
System.err.println("Failed to create directory!");
return false;
}
}
EDIT:
Now I'm trying the following, but the program is not detecting that the directory exists, even though it does.
private boolean makeDirectory(String path){
File file = new File(path);
if (file.exists()) {
System.out.println("exists");
if (file.delete()) {
System.out.println("deleted");
}
}
if (file.mkdir()) {
return true;
}
else {
System.err.println("Failed to create directory!");
return false;
}
}
RESOLVED:
(If anyone else in the future needs to know...)
I ended up doing it this way:
private boolean makeDirectory(String path){
if (Files.exists(Paths.get(path))) {
try {
FileUtils.deleteDirectory(new File(path));
}
catch (IOException ex) {
System.err.println("Failed to create directory!");
return false;
}
}
if (new File(path).mkdir()) {
return true;
}
return false;
}
You want to delete the directory first if it exists, then recreate it.
Using java.nio.file.Files
if (Files.exists(path)) {
new File("/dir/path").delete();
}
new File("/dir/path").mkdir();
and if you have FileUtils, this might be preferable as it avoids actually deleting a directory you want to be there:
import org.apache.commons.io.FileUtils
if (Files.exists(path)) {
FileUtils.cleanDirectory( new File("/dir/path"));
} else {
new File("/dir/path").mkdir();
}
You can import this library import org.apache.commons.io.FileUtils; and then you could write your code like this:
private boolean makeDirectory(){
File file = new File(TEMP_DIR_PATH + "/" + clipName);
boolean returnValue = false;
try {
FileUtils.forceMkdir(file);
returnValue = true;
} catch (IOException e) {
throw new RuntimeException(e);
}
return returnValue;
}
Check if the directory exists,
If so, delete that directory
Create directory

JFileChooser.showOpenDialog() freezing my program

I have a problem with the JFileChooser class. I am using the following class (that I did write) to load several files one after the other, and it usually works for 2 or 3 files (sometimes 1, sometimes 6, looks random even though it must not be) and at a point, it freezes at showOpenDialog(null), no exception is thrown, nothing returned either.
I really don't know where it's coming from.
Here's my class:
public class CustomFileChooser extends JFileChooser {
public File chooseFile(String windowTitle, String description, String extension, boolean mustExist) {
setDialogTitle(windowTitle);
resetChoosableFileFilters();
setAcceptAllFileFilterUsed(false);
addChoosableFileFilter(new CustomFileFilter(description, new String[] {extension}));
setSelectedFile(new File(""));
if (mustExist) {
setApproveButtonText("Open");
} else {
setApproveButtonText("Save");
}
File file = null;
while (file == null) {
if (showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = getSelectedFile();
if (mustExist) {
if (!file.canRead()) {
file = null;
JOptionPane.showMessageDialog(null, "Cannot read from the specified file!", "Error while opening the file", JOptionPane.ERROR_MESSAGE);
}
} else {
if (!file.getName().toLowerCase().endsWith(extension.toLowerCase())) {
file = new File(file.getAbsolutePath().concat(extension));
}
if (file.exists()) {
if (file.canWrite()) {
if (JOptionPane.showConfirmDialog(null, "Do you really want to overwrite this file?", "Erasing file", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) {
file = null;
}
} else {
file = null;
JOptionPane.showMessageDialog(null, "Cannot write to the specified file!", "Error while opening the file", JOptionPane.ERROR_MESSAGE);
}
}
}
} else {
return null;
}
}
return file;
}
private static final long serialVersionUID = 1L;
}
EDIT: I tryed running my program on windows and everything works fine. Do you have knowledge of a platforme related problem concerning this class/method ?
Use your code inside a code block as bellow.
private void fileChooserMethod() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
javax.swing.JFileChooser fc_file_selector= new JFileChooser();
int response = fc_file_selector.showOpenDialog(null);
//your code here
}
});
}

File is not Deleting

Am trying to deleting particular file in a folder starting with name TRTHIndicative_.
But files are not deleting,am using below code
testMethod(inputDir);
testMethod(outputFile);
private static void testMethod(String dirName){
File directory = new File(dirName);
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().startsWith("Indicative_")) {
// Delete each file
if(file.exists()){
System.out.println("File is there!");
}
if (file.delete()) {
// Failed to delete file
System.out.println("Failed to delete " + file);
} else {
System.out.println("Deleted file succsfully");
}
}
}
please check and let me know if anything wrong.
You have your if and else confused - File#delete() returns true if the file is successfully deleted. So, the condition should be reversed:
if (file.delete()) {
System.out.println("Deleted file succesfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
Mureinik is right.
I just tried your peace of code. It works fine. Just do the changes as follows:
public class Main {
public static void main(String[] args) {
File directory = new File("C:/temp");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().startsWith("blub")) {
// Delete each file
if (file.exists()) {
System.out.println("File is there!");
}
if (file.delete()) {
System.out.println("Deleted file succsfully");
} else {
// Failed to delete file
System.out.println("Failed to delete " + file);
}
}
}
}
}
Note the toLowerCase() I added. It will make your snippet easier to use.
I think you have permission error in the file you try to delete.
elToro`s answer is working fine with me as well.
Try to give read/write permission to every user
how to change file permissions in windows

FileNotFoundException with FileOutputStream open

I'm having a FileNotFoundException when i try to create a FileOutputStream. The file does exists according to file.exists. i've tried everything like file.mkdir(s) ...
I'm on a mac and i'm using gauva.
The file input is ''
java.io.FileNotFoundException: /Users/big_Xplosion/mods/Blaze-Installer/installer/test
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:194)
at com.google.common.io.Files$FileByteSink.openStream(Files.java:223)
at com.google.common.io.Files$FileByteSink.openStream(Files.java:211)
at com.google.common.io.ByteSource.copyTo(ByteSource.java:203)
at com.google.common.io.Files.copy(Files.java:382)
at com.big_Xplosion.blazeInstaller.util.DownloadUtil.downloadFile(DownloadUtil.java:80)
at com.big_Xplosion.blazeInstaller.action.MCPInstall.downloadMCP(MCPInstall.java:78)
at com.big_Xplosion.blazeInstaller.action.MCPInstall.install(MCPInstall.java:30)
at com.big_Xplosion.blazeInstaller.util.InstallType.install(InstallType.java:37)
at com.big_Xplosion.blazeInstaller.BlazeInstaller.handleOptions(BlazeInstaller.java:51)
at com.big_Xplosion.blazeInstaller.BlazeInstaller.main(BlazeInstaller.java:26)
the code in the main class.
File file = mcpSpec.value(options); //the file input given is 'test'
try
{
InstallType.MCP.install(file.getAbsoluteFile());
}
catch (IOException e)
{
e.printStackTrace();
}
The execution code The mcpTarget file has to be a directory
public boolean install(File mcpTarget) throws IOException
{
mcpTarget.mkdirs();
if (isMCPInstalled(mcpTarget))
System.out.println(String.format("MCP is already installed in %s, skipped download and extraction.", mcpTarget));
else if (isMCPDownloaded(mcpTarget))
{
if (!unpackMCPZip(mcpTarget))
return false;
}
else
{
if (!downloadMCP(mcpTarget))
return false;
if (!unpackMCPZip(mcpTarget))
return false;
}
System.out.println("Successfully downloaded and unpacked MCP");
return false;
}
Download MCP method
public boolean downloadMCP(File targetFile)
{
String mcpURL = new UnresolvedString(LibURL.MCP_DOWNLOAD_URL, new VersionResolver()).call();
if (!DownloadUtil.downloadFile("MCP", targetFile, mcpURL))
{
System.out.println("Failed to download MCP, please try again and if it still doesn't work contact a dev.");
return false;
}
return true;
}
and the DownloadUtil.DownloadFile method
public static boolean downloadFile(String name, File path, String downloadUrl)
{
System.out.println(String.format("Attempt at downloading file: %s", name));
try
{
URL url = new URL(downloadUrl);
final URLConnection connection = url.openConnection();
connection.setConnectTimeout(6000);
connection.setReadTimeout(6000);
InputSupplier<InputStream> urlSupplier = new InputSupplier<InputStream>()
{
#Override
public InputStream getInput() throws IOException
{
return connection.getInputStream();
}
};
Files.copy(urlSupplier, path);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
mcpTarget.mkdirs();
mcpTarget.mkdir();
This is the problem. You are creating a folder at the specified file. Replace this with
mcpTarget.getParentFile().mkdirs();
(or, since you use Guava, use this: Files.createParentDirs(mcpTarget))
Also, the latter is a subset of the former, so you never need to call both of the mkdir methods.

Deleting files in Android

I have a directory that contains a lot of files. I want to delete the entire directory as well as all the files in it.
I want my code to wait until every File in that directory (including the directory itself) is deleted before the next command is executed.
How do i wait?
My code is
public void wipeMemoryCard()
{
File deleteMatchingFile = new File(Environment
.getExternalStorageDirectory().toString());
try {
filenames = deleteMatchingFile.listFiles();
if (filenames != null && filenames.length > 0)
{
content = true;
for (File tempFile : filenames)
{
if (tempFile.isDirectory())
{
wipeDirectory(tempFile.toString());
tempFile.delete();
}
else
{
File file = new File(tempFile.getAbsolutePath());
file.delete();
}
}
}
else
{
deleteMatchingFile.delete();
Toast("No files to Delete");
}
}
catch (Exception e)
{
e.printStackTrace();
}
if(content == true)
{
if (filenames == null && filenames.length == 0)
{
Toast("Files Deleted");
}
}
}
private static void wipeDirectory(String name) {
File directoryFile = new File(name);
File[] filenames = directoryFile.listFiles();
if (filenames != null && filenames.length > 0)
{
for (File tempFile : filenames)
{
if (tempFile.isDirectory())
{
wipeDirectory(tempFile.toString());
tempFile.delete();
}
else
{
File file = new File(tempFile.getAbsolutePath());
file.delete();
}
}
} else
{
directoryFile.delete();
}
}
You should not run this on the UI thread. If the file deletion takes too long, the system will pop up an "Application Not Responding" error. You can do this with an AsyncTask. The documentation shows a simple way to use this to pop up a "please wait" dialog, do the time-consuming work in the background, and then dismiss the dialog.
P.S. Your method name is kind of scary! :)
You Should user Handler for this so when all files gets deleted it will send message to handler to the next task that you want to perform .
see this link for handler..
http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html
Hope you are asking about this ....
public static void DeleteRecursive(String filename) {
File file = new File(filename);
if (!file.exists())
return;
if (!file.isDirectory()) {
file.delete();
return;
}
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
DeleteRecursive(filename + "/" + files[i]);
}
file.delete();
}

Categories