Issue creating a file in android - java

I am trying to create a file inside a directory using the following code:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
File directory = cw.getDir("themes", Context.MODE_WORLD_WRITEABLE);
Log.d("Create File", "Directory path"+directory.getAbsolutePath());
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
Log.d("Create File", "File exists?"+new_file.exists());
When I check the file system of emulator from eclipse DDMS, I can see a directory "app_themes" created. But inside that I cannot see the "new_file.png" . Log says that new_file does not exist. Can someone please let me know what the issue is?
Regards,
Anees

Try this,
File new_file =new File(directory.getAbsolutePath() + File.separator + "new_file.png");
try
{
new_file.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("Create File", "File exists?"+new_file.exists());
But be sure,
public boolean createNewFile ()
Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).

Creating a File instance doesn't necessarily mean that file exists. You have to write something into the file to create it physically.
File directory = ...
File file = new File(directory, "new_file.png");
Log.d("Create File", "File exists? " + file.exists()); // false
byte[] content = ...
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content);
out.flush(); // will create the file physically.
} catch (IOException e) {
Log.w("Create File", "Failed to write into " + file.getName());
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
Or, if you want to create an empty file, you could just call
file.createNewFile();

Creating a File object doesn't mean the file will be created. You could call new_file.createNewFile() if you wanted to create an empty file. Or you could write something to it.

Related

How to save a File to any specific path in Android

I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?
Codes:
public void createFile() {
File path = new File(this.getFilesDir().getPath());
String fileName = "myfile.txt";
String value = "example value";
File output = new File(path + File.separator + fileName);
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
UPDATE :
I fixed the problem. Maybe someones to helps. Only changing this line.
File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");
You can use the following method to get the root directory:
File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC, DIRECTORY_PODCASTS, DIRECTORY_RINGTONES, DIRECTORY_ALARMS, DIRECTORY_NOTIFICATIONS, DIRECTORY_PICTURES, or DIRECTORY_MOVIES.
See more here:
https://developer.android.com/training/data-storage/files.html#WriteExternalStorage
https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)

Get the filename of the file from FileNotFoundException

I want to get the filename of the file that do not exist when a file exception occur in my java application so that i can give a short message to the user.
catch (FileNotFoundException e) {
/* what code to put here to get the filename of the file */
}
This should display the non-existing file path:
try {
//access file
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
Output, for creating a Scanner with new Scanner(new File("C:/filetest")):
C:\filetest (The system cannot find the file specified)
You cannot grap properly the filename unless you parse the stacktrace in your catch block.
You can either store the filename outside of the try block, i.e.:
String filename = ...
try {
// process file
} catch (FileNotFoundException e) {
String message = String.format("The file % could not be found.", filename);
// Show message to user
}
Or you can check whether the file exists before trying to access it:
File file = new File(filename);
if (!file.exists()) {
// Show error to user.
}

Unable to located generated file

I am generating a file using the following syntax
File file = new File("input.txt");
The problem is that it is saying that it is writing to the file but I am not able to locate where the file is created, I searched my entire workspace. The expectation was that it would be created in the same folder as my code which is executing.
Any ideas?
Rest of the code :
File file = new File("input.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
You could do a sop on the absolute path and you would get the path:
File file = new File("input.txt");
System.out.println("" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
When you create file through relative paths, Java uses System.getProperty("user.dir"). So, in your case the full path to file will be System.out.println(System.getProperty("user.dir") + "/input.txt");.

java copy file functions only works in debug mode

I have a piece of code to copy a specific file, I've used this functions for ages and it works properly.
The problem is that right now I'm writing a program with java awt/swing and my copyFile functions only works in debug mode...I can't understand why..
This is the error it throws:
can't copy directory: QQQ.wav
source file is unreadable: QQQ.wav
Error occoured QQQ.wav (The system cannot find the file specified)
But when I run the program in debug mode it works..!!
could anyone help me please???
Function copyFile:
public static void copyFile(File varFromFile, File varToFile) throws IOException {
// First make sure the source file exists, is a file, and is readable.
if (!varFromFile.exists())
System.err.println("no such source file: " + varFromFile);
if (!varFromFile.isFile())
System.err.println("can't copy directory: " + varFromFile);
if (!varFromFile.canRead())
System.err.println("source file is unreadable: " + varFromFile);
// If the destination is a directory, use the source file name
// as the destination file name
if (varToFile.isDirectory())
varToFile = new File(varToFile, varFromFile.getName());
// If the destination exists, make sure it is a writable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writable.
if (varToFile.exists()) {
if (!varToFile.canWrite())
System.out.println("destination file is unwriteable: "
+ varToFile);
} else {
// If file doesn't exist, check if directory exists and is
// writable. If getParent() returns null, then the directory is
// the current directory. so look up the user. Directory system
// property to
// find out what that is.
// The destination directory
String varParent = varToFile.getParent();
// If none, use the current directory
if (varParent == null)
varParent = System.getProperty("user.dir");
// Convert it to a file.
File vardir = new File(varParent);
if (!vardir.exists())
System.out.print("destination directory doesn't exist: "
+ varParent);
if (vardir.isFile())
System.out
.print("destination is not a directory: " + varParent);
if (!vardir.canWrite())
System.out.print("destination directory is unwriteable: "
+ varParent);
}
// If we've gotten this far, then everything is okay.
// So we copy the file, a buffer of bytes at a time.
// Stream to read from source
FileInputStream varFromSource = null;
// Stream to write to destination
FileOutputStream VarToDestination = null;
try {
// Create input stream
varFromSource = new FileInputStream(varFromFile);
// Create output stream
VarToDestination = new FileOutputStream(varToFile);
// To hold file contents
byte[] buffer = new byte[4096];
// How many bytes in buffer
int bytes_read;
// Read until EOF
while ((bytes_read = varFromSource.read(buffer)) != -1)
VarToDestination.write(buffer, 0, bytes_read);
//System.out.println("File copied !!!");
} catch (Exception e) {
System.err.println("Error occoured " + e.getMessage());
} finally {
if (varFromSource != null) {
try {
varFromSource.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
if (VarToDestination != null) {
try {
VarToDestination.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
}

Why AccessDeniedException is raising when using just created folder?

I'm creating simple object serialization, and creation of BufferedOutputStream is raising an exception AccessDeniedException. Here is the code:
Path filePath = Paths.get("c:\\temp\\");
File xmlFile = new File("c:\\temp\\");
boolean success = xmlFile.mkdirs();
if (!success && ! xmlFile.exists() ) {
// Directory creation failed
System.out.println("Failed to create a file: " + filePath);
}
try (
ObjectOutputStream objectOut = new ObjectOutputStream(
new BufferedOutputStream(Files.newOutputStream(filePath, StandardOpenOption.WRITE)))){
// Write three objects to the fi le
objectOut.writeObject(solarSystem); // Write object
System.out.println("Serialized: " + solarSystem);
} catch(IOException e) {
e.printStackTrace();
}
But directory is empty and if it doesn't not exist, it's created...
I'll repeat my comment here: you seem to try to write to a directory not to a file. Try changing filePath to a file instead.

Categories

Resources