Java Program Error saying class , interface or enum expected - java

import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException
{
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
int i;
while((i = sis.read())!=-1)
{
System.out.println((char)i);
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

I think you tried something like that. I inserted some explenations to the Exception-Handling
import java.io.FileInputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
public class Test13 {
//because all exceptions are already catched main will never throw one
public static void main(String[] args) throws IOException {
try {
//if an exception raises anywhere from here ...
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1) {
System.out.println((char) i);
}
//... to here ...
} catch (Exception ex) {
//this catch block code will be executed
ex.printStackTrace();
}
}
}

You should have
try{
//function which throws exceptions
}
catch( SpecificException e ) {
// if a specific exception was thrown, handle it here
}
catch(Exception ex) {
// if a more general exception was thrown, handle it here
}
finally{
}

Below is the updated code and its working fine.
import java.io.*;
public class Test13
{
public static void main(String[] args) throws IOException {
try {
FileInputStream fis1 = new FileInputStream("D:/abc.txt");
FileInputStream fis2 = new FileInputStream("D:/xyz.txt");
SequenceInputStream sis = new SequenceInputStream(fis1, fis2);
int i;
while ((i = sis.read()) != -1)
{
System.out.println((char) i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Related

Testing for exceptions in Opencsv CSVReader

I am trying to test exception handling when using Opencsv's CSVReader. The data will be coming from a String.
It's not working because I am (probably) not properly mocking the CSVReader, but cannot quite figure out what I need to do.
Here's the class
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvValidationException;
// other imports skipped
public class MyCsvReader {
private Path contentsAsString;
private CSVReader csvReader;
public MyCsvReader(final String contentsAsString) {
InputStream inputStream = new ByteArrayInputStream(contentsAsString.getBytes());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
csvReader = new CSVReaderBuilder(inputStreamReader)
.withSkipLines(0)
.withKeepCarriageReturn(false)
.build();
}
public void readData() {
String[] line;
try {
while ((line = csvReader.readNext()) != null) {
System.out.println("line:" + Arrays.toString(line));
}
} catch (IOException e) {
System.out.println("got IOException");
// I will be throwing a custom exception here
throw new RuntimeException(e);
} catch (CsvValidationException e) {
System.out.println("got CsvValidationException");
// and a different custom exception here
throw new RuntimeException(e);
}
}
}
and the test
public class MyCsvReaderTest {
#Test
public void testException() throws Exception {
String[] rows = {
"column1,column2,column3",
"test,abc,def"
};
String rowData = String.join("\n", rows);
CSVReader mock = Mockito.mock(CSVReader.class);
Mockito.when(mock.readNext()).thenThrow(new IOException("test"));
MyCsvReader reader = new MyCsvReader(rowData);
try {
reader.readData();
fail("Expected an exception, but call succeeded");
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
When I run it, reader.readNext() does not throw an exception
line: [column1, column2, column3]
line: [test, abc, def]
org.opentest4j.AssertionFailedError: Expected and exception, but call succeeded
... stack trace deleted
Suggestions on what I need to do? Thanks!
You don't use a mocked instance but a real one.
If the goal here is throw an exception when mock.readNext() happens you have to do something like this in order to inject your mocked instance of CSVReader:
public class MyCsvReader {
private final CSVReader csvReader;
public MyCsvReader(final CSVReader csvReader) {
this.csvReader = csvReader;
}
public MyCsvReader(final String contentsAsString) {
this(getCsvReader(contentsAsString));
}
private static CSVReader getCsvReader(final String contentsAsString) {
InputStream inputStream = new ByteArrayInputStream(contentsAsString.getBytes());
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
return new CSVReaderBuilder(inputStreamReader)
.withSkipLines(0)
.withKeepCarriageReturn(false)
.build();
}
public void readData() {
String[] line;
try {
while ((line = csvReader.readNext()) != null) {
System.out.println("line:" + Arrays.toString(line));
}
} catch (IOException e) {
System.out.println("got IOException");
// I will be throwing a custom exception here
throw new RuntimeException(e);
} catch (CsvValidationException e) {
System.out.println("got CsvValidationException");
// and a different custom exception here
throw new RuntimeException(e);
}
}
}
public class MyCsvReaderTest {
#Test
public void testException() throws Exception {
CSVReader mock = Mockito.mock(CSVReader.class);
Mockito.when(mock.readNext()).thenThrow(new IOException("test"));
MyCsvReader reader = new MyCsvReader(mock);
try {
reader.readData();
fail("Expected an exception, but call succeeded");
} catch (RuntimeException ignored) {
}
}
}

reading file using BufferedInputStream

I am new to Java programming and I was reading the a file using the BufferedInputStream(). Can someone tell me why I can't read my file? If I print obj.read(), it returns -1 everytime. Instead it should return the unicode value of every character that the stream is reading.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
while(obj2.read()!=-1)
{
System.out.print((char) obj2.read());
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}
But after introducing a local variable the code works, why???
package com.company;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("riten.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int a;
while((a=obj2.read())!=-1)
{
System.out.print((char)a);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}
You need to read from your BufferedInputStream and not from the FileInputStream. You are mixing things here.
But in addition to your code you need to properly handle streams, i.e. when you open a file you need to close those afterwards.
A fix of your code. I added a local variable to store the read character and then cast it to a character.
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int c;
while((c = obj2.read())!=-1)
{
System.out.print((char) c);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}

Java read file with scanner

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

Can't open Object Arraylist with fileio function

I'm trying to use a function to open an arraylist of objects with fileIO but right now i'm stuck. I think there is something wrong with my setter function. (The file test.txt already exists)
The following classes I'm using to get the fileio function to work
Paslijst
public class Paslijst implements Serializable {
private ArrayList<Pas> paslijst;
public ArrayList<Pas> setPaslijst(ArrayList<Pas> paslijst){
this.paslijst = paslijst;
return paslijst;
}
FileIOPas
// This function opens a file
public Paslijst openen(String filenaam)
throws IOException, ClassNotFoundException {
FileInputStream fileInputStream = new FileInputStream(filenaam);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
return (Paslijst) objectInputStream.readObject();
}
Main
public static void main(String[] args) {
FileIOPas fileiopas = new FileIOPas();
Paslijst paslijst = new Paslijst();
try {
paslijst.setPaslijst(fileiopas.openen("test.txt"));
}
catch (IOException e) {
System.out.println(" IO openen mislukt, want: " + e.toString());
}
catch (ClassNotFoundException e) {
System.out.println("class not found: " + e.toString());
}
}
You were passing wrong arguments in paslijst.setPaslijst().I have edited your class may this could Help.
public class Main {
public static void main(String[] args) {
FileIOPas fileiopas = new FileIOPas();
Paslijst paslijst = new Paslijst();
paslijst.setPaslijst(fileiopas.openen("test.txt"));
}
}
public class FileIOPas {
public ArrayList<Pas> openen(String filenaam) {
try (FileInputStream fileInputStream = new FileInputStream(filenaam);
ObjectInputStream objectInputStream = new ObjectInputStream(
fileInputStream);) {
return (ArrayList<Pas>) objectInputStream.readObject();
} catch (Exception exception) {
exception.printStackTrace();
}
return null;
}
}
public class Paslijst implements Serializable {
private ArrayList<Pas> paslijst;
public ArrayList<Pas> getPaslijst() {
return paslijst;
}
public void setPaslijst(ArrayList<Pas> paslijst) {
this.paslijst = paslijst;
}
}

Wrapping multiple AutoCloseables

try-with-resources is nice and all that, but it seems to me that it is still not sufficient for effective resource management when creating classes that wrap multiple AutoCloseable objects. For example, consider
import java.io.*;
class AutocloseableWrapper implements AutoCloseable {
private FileReader r1;
private FileReader r2;
public AutocloseableWrapper(String path1, String path2) throws IOException {
r1 = new FileReader(path1);
r2 = new FileReader(path2);
}
#Override
public void close() throws IOException {
r1.close();
r2.close();
}
public static void main(String[] args) throws IOException {
try (AutocloseableWrapper w = new AutocloseableWrapper("good-path", "bad-path")) {
System.out.format("doing something\n");
throw new IOException("doing something in main");
}
}
}
There are at least two issues with this wrapper:
If "bad-path" is invalid and causes the assignment to r2 to throw, then r1 is not closed.
If wrapper construction succeeds but then r1.close throws, then r2 is not closed.
All those issues can be addressed, but then writing the wrapper becomes quite non-trivial and error-prone, even if wrapping only two resources:
import java.io.*;
class AutocloseableWrapper implements AutoCloseable {
private FileReader r1;
private FileReader r2;
public AutocloseableWrapper(String path1, String path2) throws IOException {
r1 = new FileReader(path1);
try {
r2 = new FileReader(path2);
}
catch (IOException e) {
try {
r1.close();
}
catch (IOException e2) {
e.addSuppressed(e2);
}
throw e;
}
}
#Override
public void close() throws IOException {
IOException e = null;
try {
r1.close();
}
catch (IOException e1) {
e = e1;
}
try {
r2.close();
}
catch (IOException e2) {
if (e == null)
throw e2;
else {
e.addSuppressed(e2);
throw e;
}
}
}
public static void main(String[] args) throws IOException {
try (AutocloseableWrapper w = new AutocloseableWrapper("good-path", "bad-path")) {
System.out.format("doing something\n");
throw new IOException("doing something in main");
}
}
}
Is there some helper class or any other way to make writing wrappers easier?
You should enable the syntactic code unwrapped by the compiler....You can find the Oracle article over here :-
http://www.oracle.com/technetwork/articles/java/trywithresources-401775.html
Coming to the question,if you have a wrapper you can do something like this
#Override
public void close() throws IOException {
Throwable t = null;
try {
r1.close();
} catch (Throwable t1) {
t = t1;
throw t1;
} finally {
if (t != null) {
try {
r2.close();
} catch (Throwable t2) {
t.addSuppressed(t2);
}
} else {
r2.close();
}
}
}
Note:This will work because of precise rethrow feature in Java 7
You could use a generic resource wrapper such as:
public class CloseableChain implements AutoCloseable {
private AutoCloseable r1;
private CloseableChain r2;
public void attach(AutoCloseable r) {
if (r1 == null) {
r1 = r;
} else {
if (r2 == null) {
r2 = new CloseableChain();
}
r2.attach(r);
}
}
public void close() throws Exception {
if (r1 == null) {
return;
}
Throwable t = null;
try {
r1.close();
} catch (Throwable t1) {
t = t1;
throw t1;
} finally {
if (r2 != null) {
if (t != null) {
try {
r2.close();
} catch (Throwable t2) {
t.addSuppressed(t2);
}
} else {
r2.close();
}
}}}}
Then you could refactor your code to:
import java.io.*;
class AutocloseableWrapper implements AutoCloseable {
private CloseableChain chain;
private FileReader r1;
private FileReader r2;
private FileReader r3;
public AutocloseableWrapper(String path1, String path2) throws IOException {
chain = new CloseableChain();
r1 = new FileReader(path1);
chain.attach(r1);
r2 = new FileReader(path2);
chain.attach(r2);
// and even more...
r3 = new FileReader("whatever");
chain.attach(r3);
}
#Override
public void close() throws IOException {
chain.close();
}
public static void main(String[] args) throws IOException {
try (AutocloseableWrapper w = new AutocloseableWrapper("good", "bad")) {
System.out.format("doing something\n");
throw new IOException("doing something in main");
}
}
}

Categories

Resources