Why is the code asking to catch IOException - java

I amwriting a program using try catch but the code is asking to surround InputStreamReader and BufferedReader with try-catch to catch IOException or declare IOException using throws. But why is it asking to do so when I am using catch to the IOException.
Here is the code:
public class BufferedReader3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputStreamReader r=null;
BufferedReader br=null;
String name="";
try
{
r =new InputStreamReader(System.in);
br =new BufferedReader(r);
while(!name.equals("stop"))
{
System.out.println("Enter data: ");
name=br.readLine();
}
System.out.println("data is: "+name);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
br.close();
r.close();
}
}
}

in finally block close() calls can also throw IOException. So the compiler complains about that because IOException is of type Checked Exception you should also handle this case.
let's try to handle this with;
make use of try with resources
String name = "";
try ( InputStreamReader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r); ){
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
another try catch block in finally
InputStreamReader r = null;
BufferedReader br = null;
String name = "";
try {
r = new InputStreamReader(System.in);
br = new BufferedReader(r);
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
br.close();
r.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
make use of deprecated org.apache.commons.io.IOUtils.closeQuietly(Closeable ...)
InputStreamReader r = null;
BufferedReader br = null;
String name = "";
try {
r = new InputStreamReader(System.in);
br = new BufferedReader(r);
while (!name.equals("stop")) {
System.out.println("Enter data: ");
name = br.readLine();
}
System.out.println("data is: " + name);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally {
IOUtils.closeQuietly(br, r);
}

Related

Why am I receiving this error 'illegal start of type'?

I am getting the error in the part where it says (final (String[] args)). It would be great if somebody knows why this error is occurring. Thanks in advance! I have included the code.
public class PartOne {
private static Object BufferedReader;
public static <String> void PartOne (final (String[] args))
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("words-sowpods.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
br.close();
}
}
There are couple of things wrong here-
public static void PartOne (final (String[] args))
why u have making generic type as String even though is void
param is incorrect
Please find the correct implementation :
public static void PartOne(String[] args) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("words-sowpods.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

BufferedReader does not copy files

I 've made the code below for copying a file and its contents.
static void copyFile(File inFile, String destination) {
if (inFile.isFile()) {
try {
String str = destination + "//" + inFile.getName();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile),"UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
} else if( inFile.isDirectory()) {
String str = destination + "\\" + inFile.getName();
File newDir = new File( str );
newDir.mkdir();
for( File file : inFile.listFiles())
copyFile(file, newDir.getAbsolutePath());
}
}
The code creaes the files at the destination as it should but the .txt files are empty. The part into the while loop
bw.write(line);
doesn't work
System.out.println(line);
works.
You need to close your Writer in order to make him flush the stream. this can either be done using the newer try with ressources method (preferred):
String str = destination + "//" + inFile.getName();
// note the paranthesis here, notfing that this is has to be closed after leaving the try block.
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"))) {
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
or using a finally block:
BufferedWriter bw = null;
BufferedReader br = null;
try {
String str = destination + "//" + inFile.getName();
br = new BufferedReader(new InputStreamReader(new FileInputStream(inFile), "UTF-8"));
bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(new File(str), false), "UTF-8"));
String line;
try {
while ((line = br.readLine()) != null) {
bw.write(line);
System.out.println(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
} finally {
try {
if(bw != null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
additionally either the IDE or the compiler should warn you for not closing them.
you forget call bw.flush() method after write finished;
while((line = br.readLine()) != null ){
bw.write(line );
System.out.println( line );
}
bw.flush();
Buffered io remember call flush method;
You can try this
FileWriter fw = new FileWriter(inFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);

how can i put a filter on a CSV File stored in an Arraylist...Using Java

Iam reading a Csv file and want to put a filter on that arraylist in which the whole Csvfile is stored...
I'm new to Java Can anyone Correct me where m going wrong...
public static void main(String[] args) throws IOException {
String csvFile = "File.csv";
BufferedReader br = null;
String line ="";
ArrayList<CSVRead> alist=new ArrayList<CSVRead>();
try {
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null)
{
String StoringArray[] = line.split(",");
CSVRead Cs1 = new CSVRead((StoringArray[0]),(StoringArray[1]),(StoringArray[2]),(StoringArray[3]),(StoringArray[4]),(StoringArray[5]), (StoringArray[6]), (StoringArray[7]),(StoringArray[8]),(StoringArray[9]),(StoringArray[10]),(StoringArray[11]),(StoringArray[12]),(StoringArray[13]), (StoringArray[14]),(StoringArray[15]),(StoringArray[16]),(StoringArray[17]));
alist.add(Cs1);
}
alist.forEach(Cs1 -> System.out.println("\t" + Cs1));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
Try it
public static void main(String[] args) throws IOException {
String csvFile = "File.csv";
BufferedReader br = null;
String line ="";
ArrayList<String> alist=new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null)
{
String StoringArray[] = line.split(",");
for (String i : StoringArray){
alist.add(i);
}
}
System.out.println(alist); // print all list values
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}

FileSystemException even after closing buffers

I have this problem java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process. and I can't understand why. The System.err.println(e.getFile()); says the file that causing the exception is the groupFile, but I close the Buffers before using it with the closeBuffers().
what could be the problem with my code?
File groupFile = getFile(_grp +File.separator+ mensagem.getGroup().getName()+".txt");
ServerLogHandler group2SLH = linkHandlerToFile(groupFile);
if(group2SLH.getGroupAdmin().equals(mensagem.getUser().getName())){
try{
File temp = createFile(_grp +File.separator+"temp.txt");
group2SLH.closeBuffers();
deleteAndWrite(membro2.getName(), groupFile, temp);
Files.move(temp.toPath(), groupFile.toPath(), REPLACE_EXISTING);
temp.delete();
}catch(FileSystemException e){
System.err.println(e.getFile());
e.printStackTrace();
}
}
public void closeBuffers(){
try {
this.in.close();
this.out.flush();
this.out.close();
} catch (IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
public static void deleteAndWrite(String deleteThis, File in, File out){
try {
BufferedReader in2 = new BufferedReader(new FileReader(in));
BufferedWriter out2 = new BufferedWriter(new FileWriter(out, true));
String s;
StringBuilder sb = new StringBuilder();
while((s = in2.readLine()) != null){
if(!s.equals(deleteThis)){
sb.append(s+System.getProperty("line.separator"));
out2.write(sb.toString());
}
}
in2.close();
out2.close();
} catch (IOException e) {
e.printStackTrace();
}
}

How to display html page when server requesting?

I have a problem with showing html page form localhost. Here is my method but I just get System.out.println("IN !") in loop (eclipse console). When I'm putting http://localhost:1600/myWebPage.html adress in my browser nothing happened. I'm wondering how to show web page or just some text in browser after typing http://localhost:1600/myWebPage.html. Is this path correct ?
public class ServerWWW {
//localhost:1600/
public static void main(String[] args) {
int portServerWww = 1600;
ServerSocket ss = null;
try {
ss = new ServerSocket(portServerWww);
System.out.println("Server WWW waiting .....");
while(true) {
Socket s = ss.accept(); // block
new ServiceWWW (s).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class ServiceWWW extends Thread {
private Socket s = null;
private int counter;
public ObslugaWWW(Socket s) {
this.s = s;
}
public void run(){
try {
System.out.println("IN !"); //Loop
URL url = new URL("http://localhost:1600/myWebPage.html");
HttpURLConnection yc = (HttpURLConnection)url.openConnection();
yc.setRequestMethod("GET");
yc.setDoOutput(true);
yc.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(yc.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "OK";
while ((line = rd.readLine()) != null){
sb.append(line + '\n');
}
System.out.println(sb.toString());
yc.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories