I have two arrays that I want to print to separate files. Here's my code:
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Edges.txt"));
for (i = 0; i < bcount; i++) {
out.println(b[i][0] + " " + b[i][1]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
try {
PrintStream out = new PrintStream(new FileOutputStream(
"Nodes.txt"));
for (i = 0; i < bigbIter; i++) {
out.println(bigb[i]);
}
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
If I only use the first set of try / catch / catch, it works perfectly. But when I use both it doesn't work, giving me the errors "illegal start of type ... } catch" and "error: class, interface, or enum expected". What am I doing wrong?
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
You have an extra }, which throws off the parser and gives you lots of errors.
You should write a method to write to the file. Just pass the file name and data. You should see that you have too many closing brackets, get your IDE to highlight brackets.
Lesson is just don't copy/paste and then edit the catch block when you want it again!
Edit: Also in java 7 you can have multiple catches in one block, it is better to do this:
catch (FileNotFoundException | IOException e)
{
}
Related
I'm using "ObjectInputStream" to load serialized 2D String arrays.
The problem is, My IDE, Intellij-IDEA, will throw an error unless I put a special catch condition for a ClassNotFoundException. However, when I do that it advises, "'catch' branch identical to 'IOException' branch".
I don't know what this is implying I should do.
How can I load serialized objects without getting either advice or an error?
My code:
private String[][] getPossArray(String race, boolean isFirstName) {
String[][] retVal = new String[0][];
try {
FileInputStream fis = new FileInputStream("./res/binary_files/Human_FirstNameString[][].ser");
ObjectInputStream ois = new ObjectInputStream(fis);
retVal = (String[][]) ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return retVal;
}
Thanks to guleryuz's comment, I found out that the advice from IntelliJ was trying to tell me that I could get rid of the advice notification by changing my catch block to catch (IOException | ClassNotFoundException e) instead of having each catch statement on it's own line.
Old Catch-Block Version:
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
New Catch-Block Version:
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
I am trying to test a Java Card applet to establish a connection to a simulator such as cref:
try {
sckClient = new Socket("localhost", 9025);
InputStream is = sckClient.getInputStream();
OutputStream os = sckClient.getOutputStream();
cad = CadDevice.getCadClientInstance(CadDevice.PROTOCOL_T0, is, os);
} catch (Exception e) {
System.out.println("error");
return;
}
try {
cad.powerUp();
} catch (IOException e) {
e.printStackTrace();
} catch (CadTransportException e) {
System.out.println("error");
try {
sckClient.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
My code get stuck in powerUp without any error or exception.
I am using the sample_device and sample_platform that comes with Java Card Development Kit 3.0.5u1
I have been using Find Bugs in Eclipse and I can not figure out why some of the bugs are coming up or how to fix them. Any ideas or help would be great!
The first bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
The second bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
out.writeObject(accountMap.get(i));
I tried to change it to :
out.writeObject(accountMap.get(Integer.toString(i)));
The third bug is (Bug: Exception is caught when Exception is not thrown in banking.primitive.core.ServerSolution.saveAccounts()):
} catch (Exception e) {
e.printStackTrace();
throw new IOException("Could not write file:" + fileName);
For the first bug this is with my try block as well. I am lost. I tried to follow you post below, but I am confused. Sorry, I am very new!
public ServerSolution() {
accountMap = new HashMap<String,Account>();
File file = new File(fileName);
ObjectInputStream in = null;
try {
if (file.exists()) {
System.out.println("Reading from file " + fileName + "...");
in = new ObjectInputStream(new FileInputStream(file));
Integer sizeI = (Integer) in.readObject();
int size = sizeI.intValue();
for (int i=0; i < size; i++) {
Account acc = (Account) in.readObject();
//CST316 TASK 1 CHECKSTYLE FIX
if (acc != null) {
accountMap.put(acc.getName(), acc);
}
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
See FindBugs Bug Description:
This method uses a try-catch block that catches Exception objects, but Exception is not thrown within the try block, and RuntimeException is not explicitly caught. It is a common bug pattern to say try { ... } catch (Exception e) { something } as a shorthand for catching a number of types of exception each of whose catch blocks is identical, but this construct also accidentally catches RuntimeException as well, masking potential bugs.
A better approach is to either explicitly catch the specific exceptions that are thrown, or to explicitly catch RuntimeException exception, rethrow it, and then catch all non-Runtime Exceptions, as shown below:
try {
...
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
... deal with all non-runtime exceptions ...
}
I'm trying to close a RandomAccessFile but resource remain busy.
Code:
public boolean isOpen(RandomAccessFile f) {
try {
f.length() ;
return true ;
}
catch (IOException e) {
return false ;
}
}
this.rfmFile = new File(filePath);
try {
this.rfmRandomAccessFile = new RandomAccessFile(rfmFile, "rws");
} catch(Exception e){
}finally{
this.rfmRandomAccessFile.close();
}
while(!isOpen(this.rfmRandomAccessFile));
log.debug("I Finally Closed this RAF");
Log is not showed and thread goes in loop.
When I try to access to my resource from shell it gives me "Device or Resource busy".
The only way to access is kill java process.
When you are trying to access the RandomAccessFile length(), method, it is already closed and thus you cannot access it anymore.
You probably want to use the length() method of File. Your loop cannot work as the RandomAccessFile was already closed.
But I must admit I am clueless on the low level reason why rfmRandomAccessFile would not really be closed. It could be a side effect of your strange loop trying to get the size of a closed file.
[edit:]Could not reproduce your issue with the following piece of code:
package com.company;
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("foobar.txt");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(file, "rws");
randomAccessFile.write(new byte[]{'f'});
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(randomAccessFile !=null){
try {
randomAccessFile.close();
} catch (IOException e) {
//doh!
}
}
}
FileReader reader = null;
try {
reader = new FileReader(file);
char read = (char) reader.read();
System.out.println("what was written: "+read);
System.out.println("file size: "+file.length());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader !=null){
try {
reader.close();
} catch (IOException e) {
//doh!
}
}
}
}
}
I am currently experimenting with the encryption and decryption of objects but I am stumbling upon an EOFException every time my read method is declared. I feel like there is a lot of redundancy within my code trying to deal with all of the exceptions so it would be great if you could tell which catch/throw phrases to remove and how I can resolve this problem. Thanks.
java.io.EOFException points to the line in my code with (** **). All the other lines are NetBeans generated code.
public static void readFromBinary() throws IllegalBlockSizeException, EOFException
{
try {
BufferedReader br3 = new BufferedReader(new FileReader(noteFileName));
if (br3.readLine() != null) {
FileInputStream fINoteStream = new FileInputStream(noteFileName);
ObjectInputStream oINoteStream = new ObjectInputStream(fINoteStream);
while(true){
try{
**SealedObject sObj = (SealedObject)oINoteStream.readObject();**
Note note = (Note) sObj.getObject(new NullCipher());
noteList.add(note);
}
catch(EOFException e){
e.printStackTrace();
break;
}
catch (IllegalBlockSizeException e){
e.printStackTrace();
break;
}
catch (BadPaddingException e){
e.printStackTrace();
break;
}
catch (ClassNotFoundException e){
e.printStackTrace();
break;
}
}
oINoteStream.close();
}
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
Method Call in another class:
try{
DataStorage.readFromBinary();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (EOFException e)
{
e.printStackTrace();
}
EOFException just means you got to the end of the input. You need to close the inout and break out of the loop. You don't need to print the stack trace. It doesn't have anything to do with SealedObject specifically, just with how object streams work.
You need to decide whether you're catching this exception or throwing it. You shouldn't do both.