catch Fildnot found exception e and a try method [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.
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
}

Related

What is the better way to close IOs? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
See the codes :
I usually do like below
RandomAccessFile raf = null;
try {
// do something ...
} catch (IOException e) {
// logger
} finally {
try {
if (null != raf) {
raf.close();
}
} catch (IOException e) {
// logger
}
}
Then I see I can do this in Java8
try (RandomAccessFile raf = ... ) {
// do something ...
} catch (IOException e) {
// logger
}
It seems a good way.
Looks like Java do the job to close IO.
edit 1
Personally, I like the 2nd way.
But is it good to use and has a high performance?
With Java 7 or higher, if the resource implements AutoCloseable, best practice is to use try-with-resources:
try (
RandomAccessFile raf = /*construct it */
) {
// Use it...
}
The resource will be closed automatically. (And yes, the catch and finally clauses are optional with try-with-resources.)
Regarding the code in your question:
Re the main catch block: "log and forget" is generally not best practice. Either don't catch the exception (so the caller can deal with it) or deal with it correctly.
In the catch block in your finally where you're closing, you're quite right not to allow that to throw (you could mask the main exception), but look at the way the spec defines try-with-resources and consider following that pattern, which includes any exception from close as a suppressed exception.

How can I know a file exists or not? [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 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");

Socket not closing when timeout set [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 am new to socket programming, and have a piece of code which opens a socket and writes into it. I set the timeout for the socket as one minute, and want to close the socket and exit after I reach a certain condition.
My code is not closing the socket when the condition is met:
#Override
public void run() {
Socket socket =null;
PrintWriter writer = null;
BufferedReader reader = null;
String host = ServiceProperties.getInstance().getControllerHost();
String port = "1234;
String info="";
// TODO Auto-generated method stub
try {
socket = new Socket(host, Integer.valueOf(port));
socket.setSoTimeout(60000);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
SampleBean sBean = (SampleBean) (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sampleBean"));
info = ControllerDAO.getInstance().getControllerAndTimeScheduleInfo(sBean.getId());
writer.println("set TimeSchedule "+ info +" value ["+str+"]");
}
catch(UnknownHostException ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
}
String line="";
try {
System.out.println("BEFORE WHILE");
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
while((line= reader.readLine())!=null ) {
System.out.println(line);
if(line.contains("OK")){
System.out.println("line contains OK ");
break;
}
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("AFTER WHILE");
System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
}
catch(IOException ex) {
ex.printStackTrace();
}
try {
writer.close();
reader.close();
socket.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
});
thread.run();
Output:
//"BEFORE WHILE"
// 14:54:55
// prints line
// //prints empty line
// now it waits for like 40 seconds
// line contains OK //condition met here
// breakoutof the loop
// "AFTER WHILE"
// 14:55:55
Why is it waiting on the third iteration? The third iteration is when the condition is met, after waiting for about 40 seconds.
What am I doing wrong?
You need to catch a SocketTimeoutException (see the doc) if your request times out and then close the socket in that catch, as the socket stays valid even if there is a time out.
There are a few problems here, but I think the main one is that you are not closing the socket properly. This should be in the finally block of the try block that encapsulates the sockets, NOT in its own try block.
SO_TIMEOUT does not affect close(), try setting SO_LINGER.

try catch continue execution on exception [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.
This question was asked to me on an interview. In the below snippet the exception occur in the third line of the try block. The question was how to make the 4th line execute. The third line should be in the catch block itself. They gave me an hint 'using throw and throws'.
public void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
System.out.println("Stop");
}catch(NullPointerException e){
System.out.println("Exception");
}
}
Can any one help. Thanks in advance.
First, the exception happens on the third line of the try block - at the out.toString(), not the 2nd line.
And I am assuming you want the fourth line to execute (ie. printing stop)
There are different ways to make the next line (printing stop) to execute, if you want to simply make the Stop is printed:
public static void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
System.out.println("Stop");
}catch(NullPointerException e){
System.out.println("Stop");
System.out.println("Exception");
}
}
or given the hint that
the third line should be in the catch block itself
public static void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
Exception e = null;
try
{
out.toString();
}
catch(Exception ex)
{
e = ex;
}
System.out.println("Stop");
if(e != null)
throw e;
}catch(Exception e){
System.out.println("Exception");
}
}
There are other ways to do this, eg. finally block, etc. But with the limited amount of information given and with the goal of making it work - the above should suffice.
You could do this:
public void testCase() throws NullPointerException{
try{
System.out.println("Start");
String out = null;
out.toString();
}catch(NullPointerException e){
System.out.println("Exception");
} finally {
System.out.println("Stop");
}
}
Thorny snippet, the question was :
what's happen when you crash an internal address, here
out output, is replaced with String but it is null,
or
is it possible to print a null String, with a snippet around to focuse your attention.
you can rewrite the line : ("" + out).toString(); to pass to forth one.
'As is' it is not a technical interview, unless you have to push a second question about you have to do with the third line.
Test was : what the candidate does when he not see all parts of a problem, or when a problem is nested, is it able to ask help to understand the real problem.
EDIT after comment
Unless you comment the line, you have to capture the corrupted code :
try {
// Corrupted code to avoid
String out = null;
out.toString();
} catch (Exception e) {
// Careful (and professionnal) signal
System.out.println("out.toString() : code to repair.");
}
System.out.println("Stop"); // will appear to console

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

Categories