How to fix BufferReader issue in java [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 7 years ago.
Its been a while since I did Java and so am going through a book. As far as I can see the following code is correct however I am having trouble compiling it. I used to use Scanner, but this book is taking this approach, and I would prefer to follow it and do the exercises as explained, can anyone see what is wrong here?
import java.io.*;
class ReadFile
{
public static void main( String[] args )
{
try
{
FileReader file = new FileReader("Sheffield.data");
}
catch (IOException e)
{
System.out.println("A read error has ocurred" );
}
BufferedReader buffer = new BufferedReader(file);
String line = "";
while ((line = buffer.readLine()) != null)
{
System.out.println(line);
}
buffer.close();
}
}
The error I am getting in Windows cmd is as follows:
Simple error I know, any help will be much appreciated.
FIXED!!
BufferedReader buffer = new BufferedReader(file);
String line = "";
while ((line = buffer.readLine()) != null)
{
System.out.println(line);
}
buffer.close();
the above should all be placed in the try statement under the FileReader file = new FileReader("Sheffield.data");

file variable is created in the try block and thus BufferedReader buffer = new BufferedReader(file); doesnt have access to it. Create the reference before try and instantiate in th try block.

Related

i am getting a null-pointer at resource.length() and i am not able to figure it out why? even though the the file has data [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
class WordCount
{
String resource;
void read () throws IOException
{
File file = new File("C:\\Users\\Desktop\\read.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((resource = br.readLine()) != null)
{
resource.trim();
}
System.out.println(resource.length());
br.close();
}
}
Here you are assigning null at final step of loop:
while ((resource = br.readLine()) != null)

Java how to read a file line by line and change the specific part of the line [duplicate]

This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 3 years ago.
I am new at java and teacher gave us a project homework. I have to implement read the file line by line, slice the lines at the comma and store the parts at a multidimensional array, change the specific part of the line (I want to change the amount).
The given file:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
I tried this code but I couldn't change the specific part.
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thanks a lot!
First, you need to read the file. There are plenty of way to do it, one of them is:
BufferedReader s = new BufferedReader(new FileReader("filename"));
Which allows you to do s.readLine() to read it line by line.
You can use a while loop to read it until the end. Note that readLine will return null if you reach the end of the file.
Then, for each line, you want to split them with the coma. You can use the split method of Strings:
line.split(",");
Putting it all together, and using a try-catch for IOException, you get:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
If you really need a two dimensional array at the end, you can do:
String[][] array = new String[0][0];
array = result.toArray(array);
You then have read the file in the format you wanted, you can now modify the data that you parsed.

Reading a line from a text file

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

JAVA - reading from a file and writing to another [duplicate]

This question already has answers here:
Reading and Writing to a .txt file in Java
(4 answers)
Closed 6 years ago.
This is my code, I can't make it work properly, it gets just the last line from 3 lines total from the first text file and capitalize only that, and I cant figure out why
import java.util.Scanner;
import java.io.*;
public class AllCapitals {
public static void main(String[] args) {
String readLine;
String inFilePath = "/home/file.txt";
String outFilePath = "/home/newFile.txt";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath))) {
while ((readLine = bufferedReader.readLine()) != null) {
readLine.toUpperCase();
String upperC = readLine.toUpperCase();
System.out.println(upperC);
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outFilePath), "utf-8"))) {
writer.write(upperC);
}
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
}
}
EDIT: Forgot to say the functionallity.
I need to read 3 lines from a normal text file that goes like that
Hello.
How are you ?
Good, thank you !
And the output should be in all CAPS, but I get only the last line "GOOD THANK YOU"
That's because you recreate the output file in each iteration while reading lines from the first.
Create the output file once before you start reading, for example:
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(inFilePath));
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFilePath), "utf-8"))
) {
while ((readLine = bufferedReader.readLine()) != null) {
String upperC = readLine.toUpperCase();
System.out.println(upperC);
writer.write(upperC);
writer.write(System.lineSeparator());
}
} catch (IOException e) {
System.out.println("Error.");
e.printStackTrace();
}
Some other improvements:
Removed a pointless line readLine.toUpperCase(); that did nothing
Add a linebreak for each line, otherwise all the uppercased content would be on the same line

File not opening in Java

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!

Categories