Test if file exists - java

I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.

I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...

The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.

With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}

why dont you just catch the FileNotFound exception and take that as the file not being present.

If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}

If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}

My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.

Related

Difference between default file paths in pure Java and in Android

I’ve a problem with understanding paths in Android. I’m trying to check if file exists. It works fine in pure Java but fails in Android code and I’m giving the path in the same way (it’s just a file name). I know the file exists (in Android) because I’ve checked it by reading from it before calling to exists() method of File class. I can read the file with no problem but existence check returns false. So my question is: what is the difference between ‘normal’ and ‘android’ Java when it comes to paths?
This problem seems similar to ‘why file.exists() returns false?’ but I’ve done some reading (a lot of it) and didn’t find an answer (to both – how to check if file exists in Android and what’s the difference between paths in pure Java and Java in Android).
Below I’m pasting the code illustrating the case.
This doesn't work in Android:
//--------------------------BUTTONS ACTIONS-----------------------------------------------------
public void onSaveButtonClick(View view){
msg = textInput.getText().toString();
try {
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
fos.write(msg.getBytes());
fos.close();
Toast.makeText(getApplicationContext(), "Zapiasano!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onLoadButtonClick(View view){
loadedMsg = "";
String tmp;
try {
FileInputStream fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuffer stringBuffer = new StringBuffer();
while ((tmp=bufferedReader.readLine()) != null){
loadedMsg += tmp + "\n";
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textDisplay.setText(loadedMsg);
//----------------------FILE CHECK---------------------------------------------
File f = new File(fileName);
if(f.exists()){
textDisplay.setText("File exsists");
} else{
textDisplay.setText("File doesn't exsists");
}
}
And this works in pure Java:
public static void main(String[] args) {
String fileName = "test.file";
String str = "hello kitty!";
String loaded = "this should not load";
//-----------------SAVE------------------------------------------------
try {
FileOutputStream fos;
fos = new FileOutputStream(fileName);
fos.write(str.getBytes());
fos.close();
System.out.println("saved");
} catch (FileNotFoundException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
}
//------------------LOAD -----------------------------------------------
try {
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(isr);
loaded = bufferedReader.readLine();
isr.close();
fis.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FileExists.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(loaded);
//----------------------FILE CHECK---------------------------------------------
File file = new File(fileName);
if(file.exists()){
System.out.println("file exsists");
}
}
OUTPUT:
saved
hello kitty!
file exsists
So my question is: what is the difference between ‘normal’ and ‘android’ Java when it comes to paths?
Other Java environments assume a certain current working directory. For all intents and purposes, Android does not.
Your Android code assumes that the following three things are related:
FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
FileInputStream fis = openFileInput(fileName);
File f = new File(fileName);
The first two are related. The third is meaningless. The equivalent line would be:
File f = new File(getFilesDir(), fileName);
In Android, you always determine filesystem paths using framework-supplied methods to give you the base directories to work from (getFilesDir(), getExternalFilesDir(), methods on Environment, etc.).
Both the implementation of FileOutputStream(filename) save the file at the location given by the filename. So they kind of assume that its actually the absolute path to file.
The difference is the 'reference' they use to get to that path.
Java on your system sees that path with respect to the source location,
so you use the FileOutputStream(filename) to save file at //filename and then use File(filename) to get that file from /<reference path>/filename and you always find the file therere.
Android's FileOutputStream(filename) sees that location with respect to the files/ directory inside your package directory. While its implementation of File(pathname) see the path with respect to the root directory.
So, in android, when you write using FileOutputStream(filename), you are writing to a file /<path to your package directory>/files/filename, but when you use File(), you actually try to access a file at the root ie /filename, which, do not really exists.
Instead try:
....
File f = new File (YourActivity.this.getFilesDir().getAbsolutePath() + filename);
...

What is the simplest way to write a text file in Java?

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.

how to get a conf.txt path in eclipse

I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders.
So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer.
What I need is to be able to use the file with only the path in my workspace.
If I just put in the path, which is in the workspace it won't work.
This is how my class File looks like.
public class FileUtil {
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
return returnValue;
}
public void writeTextFile(String fileName, String s) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(s);
}
finally {
output.close();
}
}
}
I hope someone knows what to do.
Thanks!
I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.
Your project is root folder here and images as resources folder from where you can access the file using relative path.
// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));
// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt")));
If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));
This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.

Is it possible to write to a hidden file in Java?

I have figured out how to create a hidden file in Java, now I need to write large amounts of data to the file. I keep getting the following exception:SEVERE: java.io.FileNotFoundException: <filepath>\tmp (Access is denied)
Here are two approaches I took to get try and get a solution, but I get the same exception for both approaches. Note: toOverwrite is the hidden file in both cases.
File fileByteText = new File("./testFile.txt");
File toOverwrite = new File("./tmp");
//Assume toOverwrite is hidden
boolean toReturn = true;
try {
byte[] fileByteText = FileUtils.readFileToByteArray(toGetTextFrom);
FileUtils.writeByteArrayToFile(toOverwrite, fileByteText, false);
toReturn = false;
} catch (IOException e) {
bam.severe(e);
toReturn = true;
}
Approach two using the same file objects:
try {
String fileText = FileUtils.readFileToString(toGetTextFrom);
FileWriter fw = new FileWriter(toOverwrite.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(fileText);
bw.close();
toReturn = false;
} catch (IOException e1) {
bam.severe(e1);
toReturn = true;
}
You can get an Exception when you try to write to a file of type directory.
Check what method toOverWrite.isFile() returns;
if false you cannot write.
There is no magic in Unix. Just prepend a . to your filename. Under Windows, this cannot be achieved with Java. You need native commands. May this works with NIO2.

Java read a file, if it doesn't exist create it

here's my code
public String path;
public String fileName;
public static void readData() throws IOException{
try {
path="myPath"
fileName="myFileName";
fstream = new FileInputStream(path+fileName);
br = new BufferedReader(new InputStreamReader(fstream));
//do something...//
}
br.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Reading file error");
Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
I wanted to know how to check if the fstream exists. If it doesn't exist, a new file has to be created. How can I do this?
Thanks
Here's a possible solution:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile())
{
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try
{
// read data
}finally
{
r.close();
}
}
Something's missing in your code - there's a closing brace with no corresponding opening brace.
But to answer your question, create a File object first and use exists(), then createNewFile() if exists() returns false. Pass the File object instead of the filename to the FileInputStream constructor.
BTW, it would have taken you less time to google the answer than it did to type in your question here.
To check if the file filename exists in path, you can use new File(path, filename).exists().
The exists method returns true if a file or directory exists on the filesystem for the specified File.
To verify that the file is a file and not a directory, you can use the isFile method.
See the javadoc for java.io.File for more information.
if(new File("filename").exists())
...
it should do what you want.
You are already catching FileNotFoundException and this is the very place where you know that the file you wanted to read doesn't exist and you can create it.

Categories