Scanner nosuchelement exception - java

I saw people were closing the scanner and getting this. but in my case the used code is:
BlobDomain blobDomain = null;
OutputStream out = null;
try {
blobDomain = new BlobDomain();
out = blobDomain.getBinaryOutputStream();
if (status != null){
fullText = new Scanner(in).useDelimiter("\\A").next();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null)
try {
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
Exception:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)

Related

java.io.EOFException(read object)

I have 3 objects written in the file. The program outputs these 3 objects and then this java.io.EOFException error.
writing to file:
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(file))) {
planes.sort(Comparator.comparingInt(plane -> plane.productionYear));
planes.forEach(plane -> {
try {
objectOutputStream.writeObject(plane);
} catch (IOException e) {
e.printStackTrace();
}
});
objectOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
}
reading the file:
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file))) {
Object o;
while ((o = objectInputStream.readObject()) != null ){
if (o.getClass().getName().contains("Plane")) {
Plane plane = (Plane) o;
plane.productionYear = plane.productionYearCopy;
plane.speed = plane.speedCopy;
plane.engine = plane.engineCopy;
System.out.println(plane);
} else {
Ship ship = (Ship) o;
ship.productionYear = ship.productionYearCopy;
ship.speed = ship.speedCopy;
ship.engine = ship.engineCopy;
}
}
} catch (Exception e) {
e.printStackTrace();
}

How to Adding Restore setting feature by FileinputStream

So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could

How to read multiple same objects from a file

I am trying to read objects from a file(same objects of a class), using Serializable, but whenit reads all objects it gives me error IOException, java.io.ObjectInputStream$BlockDataInputStream.peekByte.
I am reading objects and then saving to list. But as it reached lets say EOF it throws error.
Here is my method:
private static void updateBook(String name) {
// TODO Auto-generated method stub
FileInputStream fis = null;
ObjectInputStream in = null;
Object obj = new Object();
List<Object> libb = new ArrayList<Object>();
File file = new File(name + ".ser");
if (file.exists()) {
try {
fis = new FileInputStream(file);
in = new ObjectInputStream(fis);
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} finally {
in.close();
//fis.close();
}
for(int j = 0; j < libb.size(); ++j) {
Book li = new Book();
li = (Book) libb.get(j);
System.out.println(li.getBookName());
}
//
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("\nThe file does not Exist!");
}
}
Can anyone please tell me how to avoid this error from while(true).
Complete error:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
On your try statement you are missing the catch clause for the EOFException:
try {
while (true) {
obj = in.readObject();
libb.add(obj);
}
} catch (OptionalDataException e) {
if (!e.eof) throw e;
//JOptionPane.showMessageDialog(null, "Done!");
} catch (EOFException eofe) {
// treat it as you like
} finally {
in.close();
//fis.close();
}
you should add:
catch (EOFException e){
// do stuffs
}
as EOFException is not being caught.

How to handle IOException when closing bufferedReader

Hi I am learning about Exceptions in Java and I encountered a problem with this situation.
public static void main(String[] args){
String path = "t.txt";
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(path));
StringBuilder sbd = new StringBuilder();
String line = br.readLine();
while(line != null){
sbd.append(line);
sbd.append(System.lineSeparator());
line = br.readLine();
}
String result = sbd.toString();
System.out.print(result);
}catch(IOException e){
System.out.println(e.getMessage());
}finally{
if (br != null)
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
}
}
when I call method close() to close the bufferedReader, it says unreported exception IOException; must be caught or declared to be thrown.
I know that JAVA 7 provides a pretty easy way to do the clean-up with
try(br = new BufferedReader(new FileReader(path))){
//....
}
but prior to JAVA 7, what can I do with this situation? adding "throws IOException" right next to the main function declaration is a way to fix that but is it a little bit complicated since I have had a catch section to catch IOExceptions
You wrapped it into another try-catch
}finally{
if (br != null)
try {
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
} catch (Exception exp) {
}
}
Now, if you care or not is another question. To my mind, your intention here is to make all best effort to close the resource. If you want, you could use flag and set it to true in the parent catch block (indicating that any following errors should be ignored) and if it's false in the close catch block, display an error message, for example...
boolean hasErrored = false;
try {
//...
}catch(IOException e){
e.printStackTrace();
hasErrored = true;
}finally{
if (br != null)
try {
br.close(); //Here it says unreported exception IOException; must be caught or declared to be thrown
} catch (Exception exp) {
if (!hasErrored) {
// Display error message...
}
}
}
prior to JAVA 7, what can I do with this situation?
You can add a try-catch in the finally block like,
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// Handle the IOException on close by doing nothing.
}
}
}
add another try catch block
...
if(br != null)
try{
br.close();
} catch (IOException io){
}
I generally code it thus:
} finally {
if (br != null) {
try {
br.close();
} catch(IOException ioe) {
// do nothing
}
}
}
In fact, I once wrote a util class containing methods such as closeStream(final InputStream stream), closeStream(final OutputStream stream), closeReader(final Reader reader), etc that hides all this stuff, since you end up using it all the time.
This is approximately how try-with-resources closes resources
BufferedReader br = new BufferedReader(new FileReader(path));
IOException ex = null;
try {
br.read();
// ...
} catch(IOException e) {
ex = e;
} finally {
try {
br.close(); // close quietly
} catch (IOException e) {
if (ex != null) {
ex.addSuppressed(e);
} else {
ex = e;
}
}
}
if (ex != null) {
throw ex;
}

Sonar is showing Bad Practice Method may fail to close stream on exception [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sonar violation: “Method may fail to close stream on exception”
I have a method that uses DataInputStream , code below :
DataInputStream in = null;
ServletOutputStream outStream = null;
FileInputStream fileIn = null;
URL searchDirectory;
try {
searchDirectory = (java.net.URL) ctx.lookup("file/testHarnessDirectory");
File file = new File(searchDirectory.getPath(), filename);
int length = 0;
outStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
byte[] byteBuffer = new byte[4096];
fileIn = new FileInputStream(file);
in = new DataInputStream(fileIn);
while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
outStream.write(byteBuffer, 0, length);
}
outStream.close();
fileIn.close();
in.close();
}
catch (NamingException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not download File", e);
}
catch (IOException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);
}
finally {
try {
if (fileIn != null) {
fileIn.close();
}
if (in != null) {
in.close();
}
if (outStream != null) {
outStream.close();
}
}
catch (IOException e) {
LOG.error("Exception", e);
throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);}}
But Sonar is giving me : Bad practice - Method may fail to close stream on exception .
I have looked up this post:Sonar violation: "Method may fail to close stream on exception", but seemed incomplete to me. I could be wrong. Could anyone let me know, what is the simple way of closing the streams?
Check this section:
try {
if (fileIn != null) {
fileIn.close();
}
if (in != null) {
in.close();
}
if (outStream != null) {
outStream.close();
}
}
and think, what will happen if fileIn.close() fails. Other two streams may remain open. Please put them in separate try-catch block. e.g.
try {
if (fileIn != null) {
fileIn.close();
}
}catch (IOException e) {
LOG.error("Exception: Could not close file stream", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close file stream", e);
}
try {
if (in != null) {
in.close();
}
}catch (IOException e) {
LOG.error("Exception: Could not close in stream"", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close in stream", e);
}
try {
if (outStream != null) {
outStream.close();
}
}
}catch (IOException e) {
LOG.error("Exception: Could not close out stream", e);
//throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close out stream", e);
}

Categories