So Im trying to get a basic reader going so that I can work with files for an authentication process later.
The problem I am having is that I get an error on my BufferedReader line that causes my try function to throw an illegal start exception and it wont run. Eclipse is showing me an error on the semicolon at the end of the br declaration and says I should be putting a { but I can't see why that would be neccessary.
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
I have tried to put that there but it breaks the entire try section.
package main;
import java.io.*;
public class file_interface
{
BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt"));
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
try
{
int count = 1;
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(count++);
sb.append(line);
sb.append("\n");
wr.write(line);
line = br.readLine();
}
}
catch (IOException e)
{
System.err.println("Error: " + e);
}
finally
{
br.close();
wr.close();
}
}
}
Any Java sentence must be inside a method. This code is not.
The fact that BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt"));
works is because is declared as a default field (no scope mark was given) in your file_interface
class and is being initialized. It is similar to do:
public class file_interface {
BufferedWriter wr;
public file_interface() {
wr = new BufferedWriter(new FileWriter("target.txt"));
}
}
Just create a method to hold your logic:
public class file_interface {
public void foo() {
//your code goes here...
//now this is not a field but a variable in the method
BufferedWriter wr = new BufferedWriter(new FileWriter("target.txt"));
BufferedReader br = new BufferedReader(new FileReader("Assign4.txt"));
//rest of your code...
try {
//...
} catch (...) {
//...
}
//...
}
}
Then just call your method in your client class. For example, a class with the main
method:
public class AMainClass {
public static void main(String[] args) {
file_interface fi = new file_interface();
fi.foo();
}
}
Another example, a class with another method:
public class SomeClientClass {
public void bar() {
file_interface fi = new file_interface();
fi.foo();
}
}
Note: You should also follow the Java Naming Conventions, so you should rename file_interface
by FileInterface
or even MyFileUtil
since interface
word sounds more to declare an, uhm, interface
.