Java: Unable to read file using FileReader [duplicate] - java

I'm trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched for something similar, and this is the code I found:
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."
I've searched for this error message, but everything I find seems to be unrelated to my situation.

Either declare a explicit constructor at your subclass that throws FileNotFoundException:
public MySubClass() throws FileNotFoundException {
}
Or surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:
public MyBaseClass() {
FileInputStream fstream = null;
try {
File inFile = new File("textfile.txt");
fstream = new FileInputStream(inFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Do something with the stream
} catch (FileNotFoundException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// If you don't need the stream open after the constructor
// else, remove that block but don't forget to close the
// stream after you are done with it
fstream.close();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.

You need to surround your code with try and catch as follows:
try {
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
} catch (FileNotFoundException fe){
fe.printStackTrace();
}
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

This is guesswork as we don't have the complete code.
From the Javadoc:
public FileInputStream(File file) throws FileNotFoundException
It means that when you do a new FileInputStream() like you do, it can come back with a FileNotFoundException. This is a checked exception, that you need to either rethrow (i.e. add 'throws FileNotFoundException' in the method where you do the new) or catch (see other try/catch responses).

Related

Cannot delete file after performing operations

Unable to delete files even after closing the corresponding readers and writers.
Permissions are present on the files
file.delete() returns false
my code
main(){
try{
File file=new File(path);// Path where the file is present
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
FileWriter writer = new FileWriter(pathOther);
BufferedWriter wr = new BufferedWriter(writer);
// Readers and writers for i/o operations
while((String str=br.readLine())!=null){
wr.write(str); // Copying to another file
}
}catch(Exception e){}
finally{
reader.close(); //close reader
writer.close(); //close writer
file.delete(); //This returns false
}
My guess as to what is going on is that you close the FileInputStream but leave the BufferedReader open, which leaves something holding on to the file handle. Then, when you try to delete the file, it returns false because something else has a handle on it.
Try the following code:
File file = new File(path);
try {
br = new BufferedReader(new FileReader(file));
// use the reader ...
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
// now close the file
file.delete();
Update:
While testing the above code I noticed something else which could also cause the observations you were seeing. If the file at path does not exist, then logically calling file.delete will also fail for this reason. So you should make sure that the file actually exists before trying to delete it. You can call file.exists() to check for this.
First, you should close the BufferedReader instead of the FileReader (the BufferedReader will in turn call close() on the FileReader):
So instead of:
reader.close(); //close reader
do:
br.close();
(and leave out the complete redundant comment).
Also, since File.delete() simply returns a Boolean and doesn't tell you why it failed, you can get more information by calling Files.delete instead:
try {
Files.delete(file.toPath());
} catch (IOException e) {
// e now contains information about why it can't delete.
}
Nothing will work call System.gc();

Reading a text file after updating it iteratively without stopping the program

I am reading a text file in my program and do some modifications in the file and then without stopping the program, I iteretively read the file and again and again, and each time I should be able to read the most recent version of the file. however, after first modification in the file, other times I am still getting that version of the file and seems other modifications are not applied.
Here is how I read the file:
public static Map<String, Float> readOwnersBiasFile() throws IOException {
FileInputStream file = new FileInputStream("ownersBias.txt");
Map<String, Float> ownerBiasMap = new HashMap<String, Float>();
//Construct BufferedReader from InputStreamReader
BufferedReader br = new BufferedReader(new InputStreamReader(file));
String line = null;
while ((line = br.readLine()) != null) {
String[] var = line.split("\\^");
ownerBiasMap.put(var[0], Float.valueOf(var[1]));
}
br.close();
return ownerBiasMap;
}
and here is how I store my modifications:
public static void storeOwnersUtilityMap(Map<String, Float> ownersUtilityMap) throws IOException {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
List<String> lines = new ArrayList<String>();
try {
fileInputStream = new FileInputStream("ownersBias.txt");
inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
bufferedReader = new BufferedReader(inputStreamReader);
String s;
String[] var;
if (bufferedReader.readLine() == null) {
for (Map.Entry<String, Float> entry : ownersUtilityMap.entrySet()) {
lines.add(entry.getKey().concat("^").concat(String.valueOf(entry.getValue())));
}
} else
while ((s = bufferedReader.readLine()) != null) {
var = s.split("\\^");
if (ownersUtilityMap.containsKey(var[0]))
s = var[0].concat("^").concat(String.valueOf(ownersUtilityMap.get(var[0])));
lines.add(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(bufferedReader);
IOUtils.closeQuietly(inputStreamReader);
IOUtils.closeQuietly(fileInputStream);
}
fileWriter(lines, "ownersBias.txt");
}
private static void fileWriter(List<String> list, String fileName) throws IOException {
File fout = new File(fileName);
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
bw.write(iterator.next());
bw.newLine();
}
bw.close();
}
And in my main method I have a loop that do some stuff along with reading and modification of the text file.
public static void main(String[] args) throws IOException, TasteException {
for(int i=0;i<10;i++){
map= readOwnersBiasFile();
do some stuff;
storeOwnersUtilityMap(map);
}
}
Should not be necessary to close the programs between re-reads, I've written programs that would read the same file and get any external changes. So that part I know works.
Now the top method readOwnersBiasFile() does not seem to close everything explicitly; I see the BufferedReader closed, but not the InputStreamReader or FileInputStream. When leaving the method, the objects have no references and therefore garbage collection should find them, timing could be an issue. I recommend try-with-resources for anything Closeable.
Operating system might cause differences, however, especially if you're both writing and reading from the same JVM. For example, in Windows you can't delete/move/rename an already open file, but *nix you can. What I don't know (partially because I don't know you're runtime platform) is whether the JVM is being tricky with file handles and tries to reuse in such a way that the changes aren't flushed from the write before things are read or whatever.
If might be worthwhile examining properties on your File object, make sure you see size changes or changed last modified dates or whatever that might indicate you're actually picking up the differences.
I also can't tell anything about the order you're calling things (in particular the first two blocks of code), whether you're doing things multithreaded or what. Open/reading/writing in a multithreaded environment might be problematic

buffered reader and file.delete

I'm creating a mini program that deletes Files using the File.delete() method but I'm having a little bit of an issue if I use the buffered Reader to read the .txt file before I delete it, it doesn't delete the file. I did come up with a solution for it: I just close the buffered reader before I delete the file. however this doesn't make sense to me as to why this is happening can anyone explain this.
import java.io.*;
import java.nio.file.Files;
public class Purge {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String sample;
boolean result = false;
BufferedReader amg = new BufferedReader(new FileReader("C:/Users/Steven/Desktop/me.txt"));
sample = amg.readLine();
amg.close();// closes the buffered reader
System.out.println("Haha I'm stille here: "+sample);
File anesu = new File("C:/Users/Steven/Desktop/me.txt");
if (anesu.exists()){
try{result = anesu.delete();
}catch( Exception x){
System.out.println("Problem Deleting File"+x);
}
catch( Throwable e){
System.out.println("Problem Deleting File Throwable"+e);
}
}else{
System.out.println("No File ");
}
System.out.println("File has been deleted: "+result);
}
}
When a stream object is garbage collected, its finalizer closes the underlying file descriptor. So, the fact that the delete only works when you added the System.gc() call is strong evidence that your code is somehow failing to close some stream for the file. It may well be a different stream object to the one that is opened in the code that you posted.
Note :
Properly written stream handling code uses a finally block to make sure that streams get closed no matter what.
If you does not want to use System.gc(), read your content with FileInputStream
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
try {
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
}
catch(Exception ex) {//TODO}
finally {
reader.close();
}
You can delete the file in the finally block.
A downside to this approach is that if an exception is thrown the file will still be deleted.
public Stream<String> readLines(Path archive) {
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
(new FileInputStream(archive.toFile()))));
return bufferedReader.lines();
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
try {
Files.delete(archive);
System.out.println("Deleted: " + archive);
} catch (IOException e) {
System.out.println("Unable to delete: " + archive);
}
}
}

Java error: Default constructor cannot handle exception type FileNotFound Exception

I'm trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched for something similar, and this is the code I found:
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."
I've searched for this error message, but everything I find seems to be unrelated to my situation.
Either declare a explicit constructor at your subclass that throws FileNotFoundException:
public MySubClass() throws FileNotFoundException {
}
Or surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:
public MyBaseClass() {
FileInputStream fstream = null;
try {
File inFile = new File("textfile.txt");
fstream = new FileInputStream(inFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
// Do something with the stream
} catch (FileNotFoundException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// If you don't need the stream open after the constructor
// else, remove that block but don't forget to close the
// stream after you are done with it
fstream.close();
} catch (IOException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.
You need to surround your code with try and catch as follows:
try {
File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
} catch (FileNotFoundException fe){
fe.printStackTrace();
}
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
This is guesswork as we don't have the complete code.
From the Javadoc:
public FileInputStream(File file) throws FileNotFoundException
It means that when you do a new FileInputStream() like you do, it can come back with a FileNotFoundException. This is a checked exception, that you need to either rethrow (i.e. add 'throws FileNotFoundException' in the method where you do the new) or catch (see other try/catch responses).

writing to a text file in java

I have the following function for writing to a file:
public void writeToFile(String data) throws IOException {
FileWriter fstream = null;
try {
fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(data);
//Close the output stream
out.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fstream.close();
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
What it does every time it is called it creates a new file and writes a new line. What I want to achieve is to check whether file exist. If not create a new file and write something, if exists then open the file and add a new line without erasing existing text. How to do that?
change your FileOutputStream constructor call to this:
fstream = new FileWriter("out.txt", true);
FileWriter takes in an additional parameter for appends, which specifies if you want to create a new file or append to an existing file
fstream = new FileWriter("out.txt", true);
http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File,%20boolean)
As there is a constructor in java's FileWriter class that can get an bool that idicates if the next "entry" is appended to the file, you should chage your
fstream = new FileWriter("out.txt");
to
fstream = new FileWriter("out.txt", true);
You can look up all those constructors in the java documentation:
http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

Categories