How can I know a file exists or not? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I wrote this code on android to learn whether a .txt file exists or not.
File file_a =new File("a.txt");
InputStream in3 = getResources().openRawResource(R.raw.b);
FileOutputStream out3 = null;
try { out3=openFileOutput("a.txt",Context.MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buff3 = new byte[1024];
int read3 = 0;
try {
while ((read3 = in3.read(buff3)) > 0) {
out3.write(buff3, 0, read3);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
in3.close();
out3.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
boolean a=file_a.exists();
It always returns false.
How can I fix this?

You have not created a file at all. All you have done is instantiate a file handle.

You can create File if its not exist
using this
if(!file.exist()){
file.createNewFile( );
}
after that when you call file.exist(); it will return true

It is not always return false.
File#exists() return true if and only if the file or directory denoted by this abstract pathname exists; false otherwise.
You are creating a new file then you should call File#createNewFile which return true if it is successfully created otherwise false.
In file is already created then you can check the File#getAbsolutePath() to verify the absolute path of file is same or not.

I found solution.I tried the read file if its get the catch block it is not exist. thanks everyone.
try {
FileInputStream deneme=openFileInput("a.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
kopyala();
e1.printStackTrace();
}

You need to provide the path to the file as well as the file name. Assuming the file is on your sd card in the root directory there:
File file_a = new File(Environment.getExternalStorageDirectory() + "/a.txt");
boolean a=file_a.exists();
If it is in a subdirectory, add the rest of the path:
File file_a = new File(Environment.getExternalStorageDirectory() + "yourpath/a.txt");
If you have written the file to internal storage, it is somewhere in the "data/data/your.package.name" path, use that.
File file_a = new File(Environment.getExternalStorageDirectory() + "date/data/your.package.name/a.txt");

Related

Contents not being written to file using Java [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am trying to get input from a JOptionPane and store what the user typed into a text file using the FileWriter class.To make sure that the input from what the user typed was being stored I wrote a system.out and what I typed in the JOptionPane appears. Unfortunately when I open the .txt file nothing I entered appears! By the way, the file path I entered is correct.
Here is my code. HELP ME!
String playername = JOptionPane.showInputDialog("What Will Be Your Character's Name?");
System.out.println(playername);
try {
FileWriter charectersname = new FileWriter("/Users/AlecStanton/Desktop/name.txt/");
BufferedWriter out = new BufferedWriter(charectersname);
out.write(playername);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Buffered writers will only write out when they're full or when they're being closed (hence the name Buffered).
So you can do this:
out.close();
which will flush the buffer and then close it. If you only wanted to flush it but keep it open for further writes (e.g. imagine you're writing a log file), you could do:
out.flush();
You'd likely want to do this when finishing up with such a resource. e.g.
BufferedWriter out = ...
try {
out.write(...);
}
catch (Exception e) {
// ..
}
finally {
out.close();
}
Or possibly using the try-with-resources constructs in Java 7, which (frankly) is more reliable to write code around.
The Java 7 version with the try() closing automatically.
try (BufferedWriter out = new BufferedWriter(
new FileWriter("/Users/AlecStanton/Desktop/name.txt"))) {
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
}
Mind the left-out / after .txt.
You should close your writer in a finally block.
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter("/Users/AlecStanton/Desktop/name.txt/"));
out.write(playername);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(out != null){
out.close();
} else {
System.out.println("Buffer has not been initialized!");
}
} catch (IOException e) {
e.printStackTrace();
}
}

File can not be executed from Java

When i try this code, it seems as executed but it is not executed.
The process builder can find the executable file. System writes the println commands.
I found some example codes but my executable file is not in same folder with java file.
private static void executeOneFile(String folderPath) {
Process p;
String exePath = path + "\\" + folderPath + "\\";
try {
p = new ProcessBuilder(exePath + "myFile.exe").start();
//p = Runtime.getRuntime().exec("myFile.exe", null , new File(exePath) );
System.out.println("p is running");
p.waitFor();
System.out.println("p ended");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
There are several problems with the code above:
You don't handle stdin/stdout properly. So maybe there is an error but you won't see it because you're not reading the output of the child process.
Next, it's always a good idea to close the child's stdin with p.getOutputStream().close() to make sure it doesn't hang waiting for input.
Lastly, the current directory of the process is the same as that of the Java VM. So if you use relative paths to write the file, it will end up somewhere but rarely where you expect. Pass the absolute path of the file to your child process to make sure the output goes where it should.

catch Fildnot found exception e and a try method [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Well I have this problem and I dont know whats wrong with the codeing,
catch (FilenotFoundException e){
system.out.println("File not found");
}
try
{
FileReader freader = new FileReader("MyFile.txt");
}
}
Its asking for what the error is?? I thought it may be the e not being capitalized is that the reason?
A try{} block should be followed by a catch{} block or finally{} block, you have reversed it.
Use like this: -
try {
FileReader freader = new FileReader("MyFile.txt");
} catch (FileNotFoundException e){
System.out.println("File not found");
}
As per Java Naming Convention: -
Class Names start with a capital letter, and all subsequent word also start with capital letter. So, FilenotFoundException should be FileNotFoundException
And, system should be -> System.
A catch{} block follows a try{} block, not the other way around.
Also, FilenotFoundException should be FileNotFoundException. I doubt it will compile with the alternate spelling. Likewise with system vs. System, as indicated in #Rohit Jain's answer.
It should be otherway. try followed by catch.
try
{
FileReader freader = new FileReader("MyFile.txt");
}catch (FileNotFoundException e){
System.out.println("File not found");
}
Since Java 7:
try( FileReader freader = new FileReader("MyFile.txt"))
{
use freader
}// try
catch( IOException e)
{
e.printStackTrace();
}
catch block should follow try
try {
//code that exception might occur
}
catch(Exception ex) {
//catch the exception here.
}
your try block should either be followed by catch or finally.
try {
//code that exception might occur
}
finally {
//close your resources here
}

Java FileOutputStream Write not working [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I followed the tutorial here: http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
And have implemented the following code as an example:
File scoreFile = new File("score.txt");
if(!scoreFile.exists()) {
scoreFile.createNewFile();
}
oFile = new FileOutputStream(scoreFile, false);
oFile.write("Score = 1".getBytes());
oFile.flush();
oFile.close();
But nothing is being written to the file score.txt.
EDIT: The whole function is given below:
// Set win or loose to score.dat.
public void setScore(boolean won, boolean reset){
out.println("setScore()");
long timePassed = (timeEnd - timeStart)/1000; // Seconds passed.
double[] prevScore = getScore(); // get previous score (Won, Lost).
// Create a writer to edit the file.
File scoreFile = new File("score.txt");
if(!scoreFile.exists()) {
try {
scoreFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(!reset){
if(won){
// Add time to Win values.
prevScore[0] += timePassed;
}
else{
// Add time to Lost values.
prevScore[1] += timePassed;
}
try {
FileOutputStream oFile = new FileOutputStream(scoreFile, false);
// Write new score.
byte[] contentBytes = (String.valueOf(prevScore[0]+" "+prevScore[1])).getBytes();
oFile.write("Bye".getBytes());
oFile.flush();
oFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
// If battle ended, delete the scores.
FileOutputStream oFile;
try {
if(!scoreFile.exists()) {
scoreFile.createNewFile();
}
oFile = new FileOutputStream(scoreFile, false);
oFile.write("Error".getBytes());
oFile.flush();
oFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I know where the file is created because I can see that it creates the file, but it doesn't populate it with any text.
That piece of code works for me... Are you looking at the right place? You can try to change the filename to "C:\\score.txt" for example to make sure you look in the right folder.
The code definitely works.(assuming you've declared oFile) .Score.txt must be in your working directory

Reading XML file in Android

I have a questions.xml file which has a list of questions for my quiz, and I'm trying to read this into a question bank in my program. I have written the following method:
// Creates the QuestionBank according to user requirements
public ArrayList<Question> createQuestionBank(String diff) {
int eventType = -1;
boolean FoundQuestions = false;
QuestionBank = new ArrayList<Question>();
// Find Question records from XML
System.out.println("check 1");
while (eventType != XmlResourceParser.END_DOCUMENT) { // Keep reading until the end of the xml file
System.out.println("check 2");
if (eventType == XmlResourceParser.START_TAG) {
System.out.println("check 3");
String Name = questionList.getName();
if (Name.equals("question")){ // Check whether the tag found is the one for question
System.out.println("check 4");
// Check difficulty of question
String diffCheck = questionList.getAttributeValue(null, "difficulty");
if (diff.equals("Any") || diff.equals(diffCheck)){
FoundQuestions = true;
System.out.println("check 5");
createandaddquestion();
System.out.println("check 6");
}
}
try {
eventType = questionList.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return QuestionBank;
}
I set some output statements to identify where my program was going wrong. The method outputs an endless cycle of check2 and never progresses to check 3, so is getting stuck at the statement:
if (eventType == XmlResourceParser.START_TAG)
I have adapted some code which I have found elsewhere and do not entirely understand what is happening. My understanding is that this statement finds the start part of a tag which I then progress to check whether this is the question tag which signifies the start of my question entry; what exactly is eventType though? Apparently it is an integer, but why does the XMLResourceParser.START_TAG return an integer when a tag is found? Surely it would make more sense to be a boolean? From the above post I don't think I need to stress that I am very new to android so please be patient! Thanks in advance.
It seems to me that eventType is never getting updated. I don't know enough about the specifics of XML parsing, but it seems that eventType needs to be updated, or else you will be stuck in an infinite loop, as you are currently being stuck. I'm guessing from looking at your code that you want to move this code down one set of brackets:
try {
eventType = questionList.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That will make sure it is called during every loop of the while() command.
I use a Sax parser and it works great:
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
You might find the Xerces2 API to be useful as well. It implements SAX and DOM parsing. http://xerces.apache.org/xerces2-j/

Categories