I'm writing a class that just reads a text file and prints out the lines. I'm getting an error on the line containing BufferedReader rd = new BufferedReader(new FileReader("file.txt")); saying that Syntax error on token ";", { expected after this token. I've tried placing it within a method, and within a try catch block as it recommends but then I'm unable to resolve the rd variable. I'm using the acm package so some of the other syntax may look different but I receive no other errors. Any help would be greatly appreciated =)
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FileReading extends ConsoleProgram {
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
Code blocks like this should be embodied inside a method or a static clause. Something like:
public class FileReading extends ConsoleProgram {
public void readFile(){
BufferedReader rd = null;
try {
rd = new BufferedReader(new FileReader("file.txt"));
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
}catch (IOException ex) {
throw new ErrorException(ex);
}finally{
try{
rd.close();
}catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
}
As answered by others, you cant provide your code in the general part of the class, it has to be within a method or static block.
By putting the code block in the constructor the problem went away.
See below for example.
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FileReading extends ConsoleProgram {
public FileReading()
{
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
}
Create a method... and inside that do this... Not directly inside the class
eg:
public void go()
{
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
Related
I am trying to learn file reading and writing, but I tried it with BufferedReader, and Scanner, it will always show the exception message. I followed the steps in the book tho. Not sure what went wrong.
package fileIO;
import java.io.*;
import java.util.*;
public class files {
public static void main(String[] args) {
String line = "";
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("Shadow.txt"));
while(br.readLine() != null){
line += br.readLine();
System.out.println(line);
}
}catch(FileNotFoundException e){
System.err.println("File not found");
}catch(Exception e){
System.out.println("Throwing exception");
}
}
}
Change your while a little bit:
while( (line = br.readLine() ) != null ) {
System.out.println(line);
}
This works for me:
import java.io.*;
class Test {
public static void main(String[] args) {
Printer.print("Shadow.txt");
}
}
public class Printer {
public static void print(String filename) {
String line;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.close();
}
}
}
I upgraded you to a try-with-resources, and fixed your while-loop. Hopefully it's also an example of how to write more modular code.
Am using nio2 to read the external file in my desktop using eclipse. I am getting the exception for the following code.
"java.nio.file.NoSuchFileException: C:\Users\User\Desktop\JEE\FirstFolder\first.txt"
Kindly advise how to resolve it? Tried using command prompt also. Getting the same exception.
public class ReadingExternalFile {
public static void main(String[] args) {
Path p1= Paths.get("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
System.out.println(p1.toString());
System.out.println(p1.getRoot());
try(InputStream in = Files.newInputStream(p1);
BufferedReader reader = new BufferedReader(new InputStreamReader(in)))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
}
}
I dont understand why you are using a Path object, you can simply make the file using the File object and just using the string as the path, and then wraping it in a file reader object then wrapping that in a buffered reader, the end should look something like this:
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
System.out.println(bfr.readLine());
bfr.close();
} catch (IOException e){
e.printStackTrace();
}
}
don't forget to close your streams after reading and writing, also use readable names (don't do what I've done, use meaningful names!)
Try below code hope this will help you.
Path p1= Paths.get("C:\\Users\\user\\Desktop\\FirstFolder\\first.txt");
try(
BufferedReader reader = Files.newBufferedReader(p1, Charset.defaultCharset()))
{
System.out.println("Inside try");
String line=null;
while((line=reader.readLine())!=null){
if (!line.equals("")) {
System.out.println(line);
}
//System.out.println(line);
}
} catch (IOException e) {
System.out.println( e);
}
Try this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\User\\Desktop\\FirstFolder\\first.txt");
FileReader freader = new FileReader(file);
BufferedReader bufreader = new BufferedReader(freader);
System.out.println(bufreader.readLine());
bufreader.close();
} catch (IOException e){
e.printStackTrace();
}
}
I'm working through the problems on code chef. I'm stuck with a problem and all its says is that I have the wrong answer. I want to test my program to see its output but it reads input from a text file and I can't figure out how to do that with eclipse, my code is below:
import java.io.*;
class Holes {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(r.readLine());
for (int i =0; i<testCases; i++)
{
int holes = 0;
String s = r.readLine();
for (int j= 0; j< s.length(); j++)
{
char c = s.charAt(j);
if (c == 'B')
holes += 2;
else if (c== 'A' || c== 'D' ||c== 'O' ||c== 'P' ||c== 'Q' ||c== 'R' )
{
holes +=1;
}
System.out.println(holes);
}
}
}
}
add folder to your eclipse project in that folder add your input file and then read it using BufferReader as follows
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("yourFolder/theinputfile.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
this is one way the other way is to pass the path as argument to your program
as it shown bellow
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(args[0]));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
how to do that when your run the application do run configuration and there you will find args you can add what ever path in it for example c:\myinput.txt
hopefully this help
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
How would you read the following text while hiding the word SECRET each times it appears ?
here is the text :
this line has a secret word.
this line does not have a one.
this line has two secret words.
this line does not have any.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class BufferedReadertest {
public static void main(String[] args) {
ArrayList <String>list = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("secretwords.txt"));
while ((sCurrentLine = br.readLine()) != null) {
list.add(sCurrentLine);
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Do you mean like
System.out.println(list.get(i).replaceAll("SECRET", "******");
I'm n seeing the need to use an ArrayList. Replace SECRET and print the message when iterating the buffered reader.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("secretwords.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine.replaceAll("SECRET", ""));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
if(line.indexOf("SECRET") > -1){
System.out.println("Has Secret");
continue;
}
import java.net.URL;
import java.io.*;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String args[]) {
try {
processHTMLFromLink(new URL("http://fwallpapers.com"));
} catch (MalformedURLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static int processHTMLFromLink(URL url) {
InputStream is = null;
DataInputStream dis;
String line;
int count = 0;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException mue) {
System.out.println(mue.toString());
} catch (IOException ioe) {
System.out.println(ioe.toString());
} finally {
try {
is.close();
} catch (IOException ioe) {
// nothing to see here
}
}
return count;
}
}
error:
java.io.IOException: Server returned HTTP response code: 403 for URL: http://fwallpapers.com
Exception in thread "main" java.lang.NullPointerException
at Test.processHTMLFromLink(Test.java:38)
at Test.main(Test.java:15)
Java Result: 1
It is working fine on browser. But I am getting null point exceptions. this code works fine with other links. can anyone help me out with this. How can I get content while i am getting 403 error.
This is an old post but if people wanted to know how this works.
a 403 means acces-denied.
There is a work around for this.
If you want to able to do this you have to set a user agant parameter to 'fool' the website
This is how my old method looked like:
private InputStream read() {
try {
return url.openStream();
}
catch (IOException e) {
String error = e.toString();
throw new RuntimeException(e);
}
}
Changed it to: (And it works for me!)
private InputStream read() {
try {
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/4.0");
return httpcon.getInputStream();
} catch (IOException e) {
String error = e.toString();
throw new RuntimeException(e);
}
}
Your mistake is swallowing the exception.
When I run my code, I get an HTTP 403 - "forbidden". The web server won't allow you to do this.
My code works perfectly for http://www.yahoo.com.
Here's how I do it:
package url;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
/**
* UrlReader
* #author Michael
* #since 3/20/11
*/
public class UrlReader {
public static void main(String[] args) {
UrlReader urlReader = new UrlReader();
for (String url : args) {
try {
String contents = urlReader.readContents(url);
System.out.printf("url: %s contents: %s\n", url, contents);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public String readContents(String address) throws IOException {
StringBuilder contents = new StringBuilder(2048);
BufferedReader br = null;
try {
URL url = new URL(address);
br = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
while (line != null) {
line = br.readLine();
contents.append(line);
}
} finally {
close(br);
}
return contents.toString();
}
private static void close(Reader br) {
try {
if (br != null) {
br.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is now a completely different question so I have edited your title.
According to your edit, you aren't getting null pointer exceptions, you are getting HTTP 403 status, which means 'Forbidden', which means you can't access that resource.