Syntax error on token "try" please delete this token [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
So I was trying to read a file, this is my piece of code;
try{
FileReader fr = new FileReader("mikuname.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
System.out.println(str + "\n");
}
br.close();
}
But when compiling I get an error saying "Syntax error on token "try" please delete this token"
Any idea how I can fix this?
Thanks!

You have inserted your try block out of the blue into a class. You may be coming from a scripting language background, where it is always legal to just write standalone action code. In Java such code must find itself either within a method or within an initializer. If you just want to run some code, then put it into the main method:
public class MyGuy {
public static void main(String[] args) {
... your try-block here ...
}
}
Note that your case is a perfect match for Java 7's try with resources:
try (FileReader fr = new FileReader("mikuname.txt");
BufferedReader br = new BufferedReader(fr))
{
... your actions ...
}

In this case, the try block must be accompanied by atleast one catch block or a finally block.
eg
try {
} catch(SomeException e){
} finally {
}

try always come with atleast one catch block
try{
FileReader fr = new FileReader("mikuname.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null){
System.out.println(str + "\n");
}
br.close();
}catch (Exception e){
//some exception information
}
check doc for more information about try..catch [link] http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html

"Any idea how I can fix this?"
put catch block after try block. this would be one of the right solution:
catch(Exception e){}

you should have a catch block corresponding to try block as follows:
try {
...
catch(<exception>) {
}

For Java 1.7+, move the declaration of your reader into the resource block:
try (FileReader fr = new FileReader("mikuname.txt");) {
// rest of block same as yours
}
catch and/or finally block is not necessary when using resources.

It looks like you're trying to use the new try with resources in Java 7. To do that, you use () around your resources:
try (
FileReader fr = new FileReader("mikuname.txt");
BufferedReader br = new BufferedReader(fr);
) {
String str;
while ((str = br.readLine()) != null){
System.out.println(str + "\n");
}
// You don't need this, it's done by the try: br.close();
}
...and of course, you have to make sure you're using Java 7, and you have to use it in a proper context (within a method or within either an instance or static initializer).

As the compiler suggested, you should remove the try keyword.
But if you actually intended to catch the IOException that could be thrown, you should add a catch clause rather than delete the try keyword.
If you're using Java 7, you can clean up your code a bit more. Right now, if there is an error while you read the file, you don't close the file and your application may run out of file descriptors. In Java 7 the try-with-resources statement has a nice way of handling this:
try (BufferedReader br = new BufferedReader(new FileReader("mikuname.txt"))) {
String str;
while ((str = br.readLine()) != null) {
System.out.println(str + "\n");
}
} catch (IOException e) {
// Do something with the IO problem that occurred while reading the file
}

Related

How to fix stream error: may fail to close stream error

I am writing a method but see this error: may fail to close stream.
According to some solutions on different posts, I have added try and catch within the finally block. I also added IOUtils.closeQuietly(fullObject, (Log) LOGGER). But it still doesn't work. Anyone can help take a look? Thanks!
S3Object fullObject = null;
StringBuffer buffer = new StringBuffer();
try {
S3Object s3Response = s3Client.getObject(s3BucketName, s3Key);
BufferedReader reader = new BufferedReader(new InputStreamReader(s3Response.getObjectContent()));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
} finally {
if (fullObject != null) {
try {
fullObject.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
IOUtils.closeQuietly(fullObject, (Log) LOGGER);
}
}
return buffer.toString();
}
You should be using Java 7+ try with resources. It will take care of closing the resources you declare in the list. Any exceptions that may be thrown in the process of closing will be dealt with appropriately. (They are either allowed to propagate, or they are "suppressed" if an exception was already propagating.)
Your code using try with resources would look like this. It is half the length of the original version AND it won't have any resource leaks. You "win" both ways.
try (S3Object s3Response = s3Client.getObject(s3BucketName, s3Key);
BufferedReader reader = new BufferedReader(
new InputStreamReader(s3Response.getObjectContent()));
)
{
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
}
Notice that I have gotten rid of fullObject which your code wasn't using.
There are actually two managed resources in the above: the s3Response and the reader. It might not be strictly necessary to close both, but (IMO) closing them anyway is the correct thing to do ... from the perspective of readability, if nothing else.
(It may also be possible to do the "read content as a string" more simply and/or more efficiently, but that is outside of the scope of this question.)
InputStreamReader implements AutoCloseable. This means that the intended use is try-with-resources:
try (InputStreamReader reader = new InputStreamReader(s3Response.getObjectContent()) {
...
}
This should always close the stream irrespective of how the block exits (i.e. through normal completion, catch or finally clauses).
The same is true for S3Object and BufferedReader. They can all be declared as resources within the same try block.
See https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for more details.

Proper exception handling on closing file read/write operations

What i want is to reduce exceptions to be thrown from a method.
As you can see i have an inner try catch in the outer catch block to avoid the exception be thrown.
Is this the normal way to do this or are there better (more elegant) ways?
Or is this approach completely false and i should just throw the exception?
public static String readText(String filename) {
String text = "";
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return text;
}
Personally I'd go for a more modern approach with either Files.readAllLines(); or Files.lines();.
Then all you need to handle is an IOException and the resources are cleaned up for you automatically.
There are several ways to be more concise in what you want to do:
Use a Java 7 feature to catch multiple exceptions in one catch:
try {...} catch(FileNotFoundException | IOException e) {...}
Use a Java 7 feature called try-with-resources so you can ommit the finally:
try (BufferedReader br =
new BufferedReader(new FileReader(filename))) {
}
In regards to throwing the exceptions or not is a design choice:
Do I want to signal errors to the upper layer?
Can I handle the error on the upper level?
If you are using Java 7 or later you can use try with resource.
try (BufferedReader br =
new BufferedReader(new FileReader(path))) {
String line = null;
while( (line = br.readLine()) != null ){
text += line;
}
}

Still resource leak after closing BufferedReader

I'm still learning Java and I need some help understanding why this code is wrong:
BufferedReader infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
infile.close();
I really don't see the problem but Eclipse keeps telling there is a resource leak and that infile isn't closed.
(one more detail, this code stands in a try block but I left it away to keep it simple)
Eclipse is complaining because the reference may not be closed (for example, in an Exception); this is where you would use a finally block - perhaps like so
BufferedReader infile = null;
try {
infile = new BufferedReader(new FileReader(file));
String regel = infile.readLine();
while (regel != null) {
// Do something with regel.
regel = infile.readLine();
}
} catch (Exception e) {
e.printStackTrace(); // Log the exception.
} finally {
if (infile != null) {
infile.close(); // close the resource.
}
}
You should have a try/catch block.
Also you should use the following instead:
while ((line = reader.readLine()) != null) {
//do something with line;
}
I think Elliott Frisch is correct and pointed out the main reason the only thing I would add is You should close the stream (in a finally block) because to ensure that any output buffers are flushed in the case that output was otherwise successful. If the flush fails, the code should exit via an exception. Here is another example similar to what you are trying to solve and make sure you look at (Guideline 1-2: Release resources in all cases) http://www.oracle.com/technetwork/java/seccodeguide-139067.html
final OutputStream rawOut = new FileOutputStream(file);
try {
final BufferedOutputStream out =
new BufferedOutputStream(rawOut);
use(out);
out.flush();
} finally {
rawOut.close();
}

Reading from .txt file returns "No line Found"

I've made a GUI and a button.
My code looks like this:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt contains the following text:
What do I contribute with when working in team work:
a. I come up with new ideas
b. I follow-up on things because I'm basically
thorough
c. I assess what is realistic and workable
d. I advocate alternative approaches objectively and unbiased
When trying to run I get "Some error No line found"
I tried removing all special characters from the text and I could read it, so I tried adding "UTF-8" to my scanner in this manner.
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
However this does not seem to do anything. I still get "No line found".
If this question has been asked before excuse me, I did a thorough search, but I either could not comprehend the question asked or the answer provided in context to my problem.
I changed my scanner to bufferedreader per Troubleshoot and Harshas example and it will now read the text even with special chars, however it won't display them correctly. I just get square boxes. It's a minor problem.
If persontest.txt is in classpath (i.e. inside jar or source folder) you can use:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
First of all, make sure persontest.txt is in your main project folder, and not a sub-folder of that, as it will not find it otherwise.
I recommend using a BufferedReader to read it line by line. Here's how:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
It's good practice to check that the line isn't empty along with checking it isn't equal to null. For example, if a line was equal to \t it would be classed as empty, but not as null.
You could simply do this using
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if you need to do it with a Scanner you can try using
Scanner reader = new Scanner(new FileInputStream("persontest.txt");

Reading in text file in Java

I wrote some code to read in a text file and to return an array with each line stored in an element. I can't for the life of me work out why this isn't working...can anyone have a quick look? The output from the System.out.println(line); is null so I'm guessing there's a problem reading the line in, but I can't see why. Btw, the file i'm passing to it definitely has something in it!
public InOutSys(String filename) {
try {
file = new File(filename);
br = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public String[] readFile() {
ArrayList<String> dataList = new ArrayList<String>(); // use ArrayList because it can expand automatically
try {
String line;
// Read in lines of the document until you read a null line
do {
line = br.readLine();
System.out.println(line);
dataList.add(line);
} while (line != null && !line.isEmpty());
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// Convert the ArrayList into an Array
String[] dataArr = new String[dataList.size()];
dataArr = dataList.toArray(dataArr);
// Test
for (String s : dataArr)
System.out.println(s);
return dataArr; // Returns an array containing the separate lines of the
// file
}
First, you open a FileWriter once after opening a FileReader using new FileWriter(file), which open a file in create mode. So it will be an empty file after you run your program.
Second, is there an empty line in your file? if so, !line.isEmpty() will terminate your do-while-loop.
You're using a FileWriter to the file you're reading, so the FileWriter clears the content of the file. Don't read and write to the same file concurrently.
Also:
don't assume a file contains a line. You shouldn't use a do/while loop, but rather a while loop;
always close steams, readers and writers in a finally block;
catch(Exception) is a bad practice. Only catch the exceptions you want, and can handle. Else, let them go up the stack.
I'm not sure if you're looking for a way to improve your provided code or just for a solution for "Reading in text file in Java" as the title said, but if you're looking for a solution I'd recommend using apache commons io to do it for you. The readLines method from FileUtils will do exactly what you want.
If you're looking to learn from a good example, FileUtils is open source, so you can take a look at how they chose to implement it by looking at the source.
There are several possible causes for your problem:
The file path is incorrect
You shouldn't try to read/write the same file at the same time
It's not such a good idea to initialize the buffers in the constructor, think of it - some method might close the buffer making it invalid for subsequent calls of that or other methods
The loop condition is incorrect
Better try this approach for reading:
try {
String line = null;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
System.out.println(line);
dataList.add(line);
}
} finally {
if (br != null)
br.close();
}

Categories

Resources