file.mkdirs() isn't working - java

Here's the code:
String folderPath = Environment.getExternalStorageDirectory() + "/AllAroundMe/Images";
File file = new File(folderPath);
if(!file.exists())
{
if(file.mkdirs());
Log.d("MyTag","Created folders succefully");
}
if(file.exists())
{
Log.d("MyTag", "folders exists: " + file.getAbsolutePath());
}
The second if never happens, and it should, because I make these dirs. What is wrong with my code?
BTW, everytime I run this program, it always goes in the first condition.

I think you should remove that semi-colon after that inner if: -
if(file.mkdirs()) {
Log.d("MyTag","Created folders succefully");
}
P.S: - That is why you should always use curly braces, even if you have only single statement if, so that you don't do such kind of mistakes.

Make sure that you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in your android.manifest file.
Also, it would be better to construct your file object like this:
String folderPath = "AllAroundMe/Images";
File file = new File(Environment.getExternalStorageDirectory(), folderPath);

Related

Creating file on filesystem with java.io.File

I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path.
Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
You can use new File("folder", newFileName.getText() + ".properties") which will create a file reference to the specified file in the folder directory relative to the current working directory
You should make sure that the directory exists before calling createNewFile, as it won't do this for you
For example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Trivially I missed that new File(".").getAbsolutePath() returns the project's absolute path with the . at the end so my folder whould be called as .folder. Next time I'll check twice.

reading an external file using TextIO

I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.

Java: renameTo() function failing

Java
The code below was written to read all files in, and send the data to another method (setOutput()), and then call a method to rename the last read file to another directory, and then delete the original. Everything seems to work up until the smdrCleanup() method is called. The renameTo() is failing.
From what I understand, if a FileReader is wrapped in a BufferedReader, I only need to call BufferedReader.close() to release the last read file... which I am doing here.
I have also seen where if the file were still "open", being scanned by anti-virus programs, or otherwise locked by a process, the renameTo() function would fail. I have used Process Explorer to review what may have it locked, and I don't see anything locking it.
I have my method setup to throw any kind of IOExceptions, but I am not getting any exceptions. Everything runs, but the console merely says that the file was not copied.
I am running Eclipse Helios Release 2, Windows 7 Ultimate, local administrator, UAC disabled.
Any help would be greatly appreciated.
public void smdrReader(String path, String oldPath) throws IOException
{
output = null; //nullify the value of output to avoid duplicate data
File folder = new File(path); //setting the directory for raw data files
File[] listOfFiles = folder.listFiles(); //array of files within the folder/directory
//For loop to iterate through the available files, open, & read contents to String Buffer.
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile()) //verifying next entry in array is a file
{
File fileName = new File(listOfFiles[i].getName());//getting file name from array iteration
StringBuffer fileData = new StringBuffer(2048);//establishing StringBuffer for reading file contents into
BufferedReader reader = new BufferedReader(new FileReader(path + fileName));//reader to actually access/read file
String readData = String.valueOf(reader);//String variable being set to value of the reader
fileData.append(readData);//appending data from String variable into StringBuffer variable
setOutput(fileData);//setting the value of "output" to the value of StringBuffer
fileData.delete(0, i);
reader.close();//closing the reader (closing the file)
smdrCleanup(oldPath,fileName.toString());//calling method to move processed file and delete original
}
}
}
//method to rename input file into another directory and delete the original file to avoid duplicate processing
public void smdrCleanup(String oldPathPassed, String fileNamePassed) throws IOException
{
File oldFile = new File(oldPathPassed);//establishing File object for path to processed folder
File fileName = new File(fileNamePassed);//establishing File object for the fileName to rename/delete
String oldFilePath = oldFile.toString();
boolean success = fileName.renameTo(new File(oldFilePath + "\\" + fileName + ".old"));//attempting to rename file
if (!success) //checking the success of the file rename operation
{
System.out.println("The File Was NOT Successfully Moved!");//reporting error if the file cannot be renamed
}
else
{
fileName.delete();//deleting the file if it was successfully renamed
}
}
oldFile.toString(); returns the full path of the file including its file name, so if your old file path is c:\path\to\file.txt, oldFilePath + "\\" + fileName + ".old" will be c:\path\to\file.txt\file.txt.old.
Since there is no folder c:\path\to\file.txt, it fails. change it to
boolean success = fileName.renameTo(new File(oldFilePath + ".old"));
And you should be good to go.
File.renameTo can fail for any number of reasons:
Many aspects of the behavior of this
method are inherently
platform-dependent: The rename
operation might not be able to move a
file from one filesystem to another,
it might not be atomic, and it might
not succeed if a file with the
destination abstract pathname already
exists. The return value should always
be checked to make sure that the
rename operation was successful.
But there's not much feedback on why it fails. Before calling renameTo, verify that the file you're moving exists, and the parent directory you are moving it to also exists, and canWrite(). Are these on the same disk volume? If not, it might fail.
*EDIT: Code sample added *
Try something like the following. Modifications:
Accepts File objects instead of Strings
Uses 2-arg File constructor to create a child File object in a parent directory
Better error checking
This might give you some clues into what is failing.
public void smdrCleanup(File oldPathPassed, File fileNamePassed) throws IOException {
if (!oldPathPassed.exists() || !oldPathPassed.isDirectory() || !oldPathPassed.canWrite() ) throw new IOException("Dest is not a writable directory: " + oldPathPassed);
if (!fileNamePassed.exists()) throw new IOException("File does not exist: " + fileNamePassed);
final File dest = new File(oldPathPassed, fileNamePassed + ".old");
if (dest.exists()) throw new IOException("File already exists: " + dest);
boolean success = (fileNamePassed).renameTo(dest);//attempting to rename file
if (!success) //checking the success of the file rename operation
{
throw new IOException("The File Was NOT Successfully Moved!");
} else {
// file was successfully renamed, no need to delete
}
}

Java. Files and folders. Can't define the type

Good Day!
I wrote the method in Java which must search files in folders and do some operations with them.
So the problem is that when I try to check what I have (file or dir) I receive nothing in both cases! But as i can see paths look correct.
How can I fix this problem?
Here is the code:
public void searchInDir(){
File inputFile = new File( this.fileName );
String[] namesOfFilesDir = inputFile.list();
for ( int i = 0; i < namesOfFilesDir.length; i++ )
{
String normalPath = this.getNormalPath(inputFile.getCanonicalPath()); //C:\User -> C:\\User
// Two separators for correcting path to file
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
System.out.printf("FileName=%s, Path=[%s]\n", namesOfFilesDir[i], pathToCurrentFile);
System.out.println(f.isDirectory());//False
System.out.println(f.isFile());//False too
//Some other code
}
}
For example this.fileName consists path to folder ( and this folder consists one folder and 2 files).
I got next:
FileName=Readme.txt, Path=[C:\\workspace\\Grep\\t\\Readme.txt]
false
false
FileName=t2, Path=[C:\\workspace\\Grep\\t\\t2]
false
false
FileName=test.txt, Path=[C:\\workspace\\Grep\\t\\test.txt]
false
false
Ok. Program says that.
Lets print next code as an example.
File f = new File("C:\\workspace\\Grep\\t\\Readme.txt");
System.out.println(f.isFile());
Program will print ”True”.
This part makes no sense:
String pathToCurrentFile = normalPath + File.separator + File.separator + namesOfFilesDir[i];
File f = new File( pathToCurrentFile, namesOfFilesDir[i] );
Even if we forget about the double separator for the time being, it makes no sense to first construct the file name by adding namesOfFilesDir[i], then construct a File() object using the two-argument constructor which basically adds namesOfFilesDir[i] once more. Try printing f.getAbsolutePath() and you'll see what I mean. It should have probably been something like:
File f = new File( normalPath, namesOfFilesDir[i] );
Probably the file doesn't exist, so it is neither a file nor a directory. Try printing the output of f.exists() as well.
Did you notice the duplicate file separator in your path?
I think that perhaps your paths are not correct. Both isFile() and isDirectory() only return true if the file/directory actually exists. Have you tried calling exists() on the file? Also, I'm suspicious of what your getNormalPath() method is doing - I think it might be mangling the filenames.
The 1st System.out.println is missleading!
It would have been better to output the path of f.
Anyway, according the output:
FileName=Readme.txt, Path=[C:\workspace\Grep\t\Readme.txt]
f will be C:\workspace\Grep\t\Readme.txt\Readme.txt
that is, namesOfFilesDir[i] is being appended twice!
It would be easier/better to work just with instances of File directly:
File inputFile = new File(this.fileName);
File[] files = inputFile.listFiles();
for (File f : files) {
System.out.printf("FileName=%s, Parent=[%s]\n", f.getName(), f.getParent());
System.out.println(f.isDirectory());
System.out.println(f.isFile());
//Some other code
}

How do I refer to a directory in Java?

I'm running Windows and I'm trying to refer to a directory. My function starts off like this:
File file = new File("C:\\somedir\\report");
if (!file.exists()) {
file.mkdirs();
}
doStuffWith(file);
I got a NullPointerException within the doStuffWith function, when I tried to call listFiles. Well I looked in C:\somedir and what did I find - there is a file called "report" with no extension, and also a directory called "report"! What seemed to happen was that the file object was referring to the report file rather than the directory. How do I make sure that I am referring to the directory and not the file?
one way to go about is to pass the file object corresponding to "C:\somedir" to the method and inside the method, do a listFiles() and walk through the contents, each time checking for file name and if it is "report", do a isDirectory(). proceed with actual processing when this returns true.
i think there is a isDirectory() method that will tell you if it is a directory
--EDIt
that's what I get for being up so early. I ran your code locally and it works fine for me. Was able to create new files, read directory contents, etc. What else are you trying to do?
I don't understand the problem this works fine for me:
public class MkDir {
static void doStuff(File dir) {
if ( dir.isDirectory() ) {
File[] listFiles = dir.listFiles();
for ( File f : listFiles ) {
System.out.println( f.getName() );
}
}
}
public static void main(String[] args) {
File file = new File( "C:\\dev\\rep2\\rep" );
if ( !file.exists() ) {
file.mkdirs();
}
doStuff( file );
}
}
Check if your file system has had case sensitivity enabled (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\kernel\ dword:ObCaseInsensitive in the registry.)
If so, you may be getting bitten by a case-related issue. One way to check:
String someName = "./nameNotUsedYet";
boolean first = new File(someName).mkdirs();
boolean second = new File(someName.toUpperCase()).mkdirs();
System.out.println("first = " + first + ", second = " + second);
If both mkdirs() calls succeeded, you know you have a case related complication. If so, ensure that you get the case for "C:\somedir\report" exactly right.

Categories

Resources