I am trying to read a line from a text file, but the program keeps returning an error stating that the file's name cannot be located. Any ideas on how to solve the problem.
Source code:
import java.io.FileReader;
import java.io.BufferedReader;
public class Cipher {
public String file_name;
public Cipher(){
file_name = "/Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt";
}
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
Cipher cipher_1 = new Cipher();
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}
}
}
Upon debugging this is what I get,
Error:(25, 14) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Error:(30, 43) java: unreported exception java.io.IOException; must be caught or declared to be thrown
The above two lines are where :
Variable fr is initialized.
The while loop.
You are getting these errors because the methods and constructors you are calling throw exceptions. These either need to be caught with a try/catch block or be declared in the method signature.
These errors are compile time errors, not runtime. It's not saying that the file doesn't exist, but that you need to catch an exception just in case that is true.
Oracle Tutorial
Please Enter the complete path that is the Drive along with the folder location.
C:\....\Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt
Like this. It should be like when you copy paste in the explorer you can jump to the file directly.
If using MAC then, right click on the text file and properties and copy the location and paste it in your code.
In your code, below lines need to catch
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
Use try-catch block or throws Exception to handle it.
Your file path should include the entire path for example:
"C:\\Users\\John Doe\\Desktop\\Impactor_0.9.41.txt"
Notice I used an extra '\' but I'm not sure if that matters, however I always do that.
Also for clarity you could also change your br and fr like this, however what you did is fine as well. But it is important to do the opening of files in a try-catch block like this:
try{
br = new BufferedReader(new FileReader(cipher1.file_name));
} catch(FileNotFoundException e){
e.printStackTrace();
}
Also when reading and printing out file to console, put it in try catch:
try{
String current_line;
while((current_line = br.readLine()) != null){
System.out.println(current_line);
current_line = br.readLine();
}
} catch(IOException e){
e.printStackTrace();
}
try{
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}catch(Exception e)
e.printStackTrace();
{
You need to handle the exceptions generated by your reader
Related
This question already has answers here:
Java unreported exception [duplicate]
(2 answers)
Closed 2 years ago.
so I was tasked with writing and reading TextFiles in java, and I managed to successfully write a TextFile and display the contents (First Names) in the new file called "FirstNames". I am supposed to use the try-catch block to accomplish this task, however, I am unable to successfully read the file back, as it produces some errors that I am unable to fix. Any help would be greatly appreciated!
My Code:
// Import file
Import java.io.*;
// Import file reader
import java.io.FileReader;
// Import IOException to handle any errors
import java.io.IOException;
// Create class and method
class Main {
public static void main(String[] args) {
// Start a try-catch block
try {
// Initialize the new objects
FileWriter fw = new FileWriter("FirstNames");
BufferedWriter bw = new BufferedWriter(fw);
// Create a String array to store the first names
String names[] = new String[] { "Hussain", "Ronald", "John", "James", "Robert", "Michael", "William", "David",
"Joseph", "Daniel" };
// Output the first names in the textfile
for (int x = 0; x < 10; x++){
bw.write(names[x]);
bw.newLine();
}
bw.close();
fw.close();
// Catch any errors
} catch (Exception e) {
System.out.println("An error occured!");
}
// Experiencing issues starting from here:
// Create another try-catch block to read the file
try {
// Initialize the new objects
FileReader fr = new FileReader("FirstNames.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
// Start a while loop to output the line
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
fr.close();
} catch (NullPointerException e1) { // I have put it to NullPointerException only to see the errors I'm getting for now
// System.out.println("An Error Occured!");
}
}
}
My Output:
Your problem was you were writing FirstNames and then trying to read FirstNames.txt
I've made some enhancements below to use Try-with-resources which offers the benefit of not having to close the resource at the end of use.
I've also replaced the file name with a single variable that holds the string name. ("extract to variable" under your refactor menu in IntelliJ)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Main {
public static void main(String[] args) {
// By deduplicating the filename you will remove the chance for errors.
String fileName = "FirstNames";
try (FileWriter fw = new FileWriter(fileName)) {
// Initialize the new objects
BufferedWriter bw = new BufferedWriter(fw);
// should probably be a public static final String[] class field.
String names[] = new String[]{"Hussain",
"Ronald",
"John",
"James",
"Robert",
"Michael",
"William",
"David",
"Joseph",
"Daniel"};
// Output the first names in the textfile
for (String name : names) {
bw.write(name);
bw.newLine();
}
bw.close();
} catch (IOException ex) {
ex.printStackTrace(); // read the stack trace to understand the errors
}
// Now TRY reading the file
try (FileReader fr = new FileReader(fileName)){
// Initialize the new objects
BufferedReader br = new BufferedReader(fr);
String line;
// Start a while loop to output the line
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("Catches errors related to br.readLine(), br.close() and new FileReader");
e.printStackTrace();
}
}
}
Hopefully not too far removed from your original code that it still makes sense.
As others have mentioned, in a real-world situation, you may want to throw all/some errors higher up the call stack so they can be handled by a centralised error handler (so that all error handling logic is in one place rather than scattered all over the place).
At the moment I've just put ex.printStackTrace() and allowed execution to continue. This could result in multiple stack traces to be printed out which can be confusing.
Essentially start with the first error in the output and if you fix that, you may fix all the problems, otherwise re-run and look at the next first error in the console... and so on. Eventually when you've fixed all errors the code will run :)
I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.
I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.
If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.
I don't know why this happened, but the problem seemed that I did not enter the complete path for the file even though the file was in the same folder. Ideally if the file is in the same folder then I wouldn't need to enter the entire pathname.
Try doing a check if it exists first:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */
I am working on a simple save system for my game, which involves three methods, init load and save.
This is my first time trying out reading and writing to/from a file, so I am not sure if I am doing this correctly, therefore I request assistance.
I want to do this:
When the game starts, init is called. If the file saves does not exist, it is created, if it does, load is called.
Later on in the game, save will be called, and variables will be written to the file, line by line (I am using two in this example.)
However, I am stuck on the load function. I have no idea what do past the point I am on. Which is why I am asking, if it is possible to select a certain line from a file, and change the variable to that specific line.
Here is my code, like I said, I have no idea if I am doing this correctly, so help is appreciated.
private File saves = new File("saves.txt");
private void init(){
PrintWriter pw = null;
if(!saves.exists()){
try {
pw = new PrintWriter(new File("saves.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}else{
try {
load();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(new File("saves.txt"), true));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
pw.println(player.coinBank);
pw.println(player.ammo);
pw.close();
}
public void load() throws IOException{
BufferedReader br = new BufferedReader(new FileReader(saves));
String line;
while ((line = br.readLine()) != null) {
}
}
I was thinking of maybe having an array, parsing the string from the text file into a integer, putting it into the array, and then have the variables equal the values from the array.
Seems like your file is a key=value structure, I suggest you'll use Properties object in java.
Here's a good example.
Your file will look like this:
player.coinBank=123
player.ammo=456
To save:
Properties prop = new Properties();
prop.setProperty("player.coinBank", player.getCoinBank());
prop.setProperty("player.ammo", player.getAmmo());
//save properties to project root folder
prop.store(new FileOutputStream("player.properties"), null);
Then you'll load it like this:
Properties prop = new Properties();
prop.load(new FileInputStream("player.properties"));
//get the property value and print it out
System.out.println(prop.getProperty("player.coinBank"));
System.out.println(prop.getProperty("player.ammo"));
Reading and writing are pretty much symmetric.
You're writing player.coinBank as the first line of the file, and player.ammo as the second line. So, when reading, you should read the first line and assign it to player.coinBank, then read the second line and assign it to player.ammo:
public void load() throws IOException{
try (BufferedReader br = new BufferedReader(new FileReader(saves))) {
player.coinBank = br.readLine();
player.ammo = br.readLine();
}
}
Note the use of the try-with-resources statement here, which makes sure the reader is closed, whatever happens in the method. You should also use this construct when writing to the file.
Im trying to read a simple text file with contents
input.txt
Line 1
Line 2
Line 3
But it always goes to the exception and prints Error.
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR");
}
}
}
Im using Eclipse as my IDE if that makes a difference. I've tried this code on http://www.compileonline.com/compile_java_online.php
and it runs fine, why wont it run in Eclipse?
give complete file path like "C:\\folder_name\\input.txt" or place input.txt inside src directory of eclipse project.
public class Main {
public static void main(String args[]){
List<String> text = new ArrayList<String>();
try{
BufferedReader reader = new BufferedReader(
new FileReader("input.txt")); //<< your problem is probably here,
//More than likely you have to supply a path the input file.
//Something like "C:\\mydir\\input.txt"
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}catch(IOException e){
System.out.println("ERROR"); //This tells you nothing.
System.out.println(e.getMessage()); //Do this
//or
e.printStackTrace(); //this or both
}
}
}
You most likely have a bad path. Consider this main instead:
public class Main {
public static void main(String args[]) throws Exception {
List<String> text = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
for (String line; (line = reader.readLine()) != null; ) {
text.add(line);
}
System.out.println(text.size()); //print how many lines read in
reader.close();
}
}
The "throws Exception" addition allows you to focus on the code, and consider better error handling later. Also consider using File f = new File("input.txt") and use that, because it allows you to print out f.getAbsolutePath() which tells you the filename it was actually looking for.
Changing input.txt to src\\input.txt solved the problem!
I guess it was because the current directory isnt actually the src folder its the parent,
Thanks for the help!