I'm working on creating simple address book using text file but my code is throwing too much errors in deleting a String method.It shows IO Exceptions at mostly places and when the IO Exceptions are resolved then compiling error cannot find symbol occurs at 5 places in some identifiers. Here is my code:
public void DeletePerson(){
try {
File file = new File("AddressBook.txt");
File temp = File.createTempFile("file", ".txt", file.getParentFile());
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream(file), Charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new
FileOutputStream(temp), Charset));
//More code ...
} finally {
if (writer != null) {
System.out.println("Closing PrintWriter");
writer.close();
} else {
System.out.println("PrintWriter not open");
}
file.delete();
temp.renameTo(file);
}
}
Output:
C:\java\AddressBook>javac AddressBook.java
AddressBook.java:50: error: cannot find symbol
if (writer != null) {
^
symbol: variable writer
location: class AddressBook
AddressBook.java:52: error: cannot find symbol
writer.close();
^
symbol: variable writer
location: class AddressBook
AddressBook.java:57: error: cannot find symbol
file.delete();
^
symbol: variable file
location: class AddressBook
AddressBook.java:58: error: cannot find symbol
temp.renameTo(file);
^
symbol: variable file
location: class AddressBook
AddressBook.java:58: error: cannot find symbol
temp.renameTo(file);
^
symbol: variable temp
location: class AddressBook
I'm creating address-book and finding problem in deleting person's name method. Firstly i have to take input from user i.e. name of the person then i have to check the text-file(read the file) and find the matched word and then delete it from addressbook.
I have also made other methods to delete the name but they didn't work thoroughly.
Kindly check the code and resolve the problem please.
Your File and PrintWriterObject inside the try block
You can try to use it.
File file = new File("AddressBook.txt");
PrintWriter writer = new PrintWriter(new FileWriter(file,Charset.forName("UTF-8")));//use "throws IOException" in your method.
try{
//some java code
}finally{
if (writer != null) {
System.out.println("Closing PrintWriter");
writer.close();
} else {
System.out.println("PrintWriter not open");
}
file.delete();
}
Related
I have run into a situation when writing code in Java. The error mentions that in my code newLine() has private access in PrintWriter I have never gotten this error and it worries me as I cannot understand why newLine would be private to my variable PrintWriter
Below will be my error messages and part of my code where this issue comes from.
Errors:
:75: error: newLine() has private access in PrintWriter
savingsFile.newLine();
^
:77: error: newLine() has private access in PrintWriter
savingsFile.newLine();
^
:96: error: cannot find symbol
while((str1=savingsFile.readLine())!=null){
^
symbol: method readLine()
location: variable savingsFile of type Scanner
3 errors
Code:
public static void writeToFile(String[] months, double[] savings) throws IOException{
PrintWriter savingsFile = null;
try {
savingsFile = new PrintWriter(new FileWriter("E:/savings.txt", true));
} catch (IOException e) {
e.printStackTrace();
}
//code to write to the file and close it
int ctr = 0;
while(ctr<6){
savingsFile.write(months[ctr]);
savingsFile.newLine();
savingsFile.write(savings[ctr]+"");
savingsFile.newLine();
ctr = ctr + 1;;
}
savingsFile.close();
}
public static void readFromFile(String[] months, double[] savings) throws IOException{
String str1, str2;
Scanner savingsFile = null;
try {
savingsFile = new Scanner(new File("E:/savings.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//code to read the file, load data in the array and close file
str1 = savingsFile.nextLine();
System.out.println(str1);
int ctr = 0;
while((str1=savingsFile.readLine())!=null){
System.out.println(str1);
}
savingsFile.close();
}
PrintWriter does not have a public newLine() method (see the Javadoc). Just write a newline character "\n" to make a new line, or call println() with no arguments.
Scanner does not have a readLine() method. You probably meant nextLine()
It seems like newLine() is a private method in PrintWriter what means that you can't invoke it externally from some other class that instantied PrintWriter as object.
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
I have a program that saves on a file. The current code is set for the file to save on a specific path, but when I run the program from a different computer the program doesn't work and I need to change the path everytime.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
I placed the file in the a subfolder in the program with the name ConsID and I tried changing the path file to
String csvFileToRead = "..\\ConsID\\consID.csv";
But the file can't be read from the program.
String csvFileToRead = "E:\ryan_assignment_sit2\ConsID\consID.csv";
The above path will only be applicable to windows. If you execute the program in linux environment you will get an Filenotfoundexception. Eventhough you change the file, again you are hardcoding the file path.
Better you can get it as runtime parameters so that the program will be executed irrespective of OS.
If you are running you program from command line then you can place the csv file in your classpath (root folder where the class files are generated) and refer to it as below:
BufferedReader br = new BufferedReader(ClassLoader.getResourceAsStream("consID.csv"));
THIS IS MY CODE
import java.IO.*;
class jed {
public static void main (String args[]){
BufferedReader datain = new BufferedReader(new InputStreamReader(System.in));
String name =" ";
System.out.print("What is your name?:");
try{
name = datain.readline();
} catch(IOException e) {
System.out.print("Error");
}
System.out.print("Your name is" + name); } }
THIS IS THE ERROR
D:\>javac jed.java jed.java:1: error: package java.IO does not exist
import java.IO.*; ^ jed.java:4: error: cannot find symbol
BufferedReader datain = new BufferedReader(new
InputStreamReader(System.in)); ^ symbol: class BufferedReader
location: class jed jed.java:4: error: cannot find symbol
BufferedReader datain = new BufferedReader(new
InputStreamReader(System.in)); ^ symbol: class BufferedReader
location: class jed jed.java:4: error: cannot find symbol
BufferedReader datain = new BufferedReader(new
InputStreamReader(System.in));^ symbol: class InputStreamReader
location: class jed jed.java:10: error: cannot
find symbol catch(IOException e){^ symbol: class IOException location: class jed 5 errors
I will appreciate any help I can get to fix this issue. Thank you
Java is case sensitive.
Your import is wrong. Change
import java.IO.*;
to
import java.io.*;
In defence of the compiler it does actually tell you the problem clearly:
error: package java.IO does not exist import java.IO.*;
Java is case sensitive. You should import java.io.*, instead of java.IO.*.
You have to change .readline()
to .readLine(), because java is case sensitive.
Basically I am trying to take information from a text file and turn it into a string. The code I have is:
FileInputStream inputStream = new FileInputStream("filename.txt");
try
{
String everything = IOUtils.toString(inputStream);
}
finally
{
inputStream.close();
}
the error message I get is -->
java:53: cannot find symbol
symbol : class IOUtils
location: class CheckSystem
I assumed this was because of my imports, but I have io and util and even text imported (just as below)
import java.util.*;
import java.text.*;
import java.io.*;
Why can't I access the IOUtils class and its methods? If that cannot be answered, an alternative but very simple means of reading a text file into a string would be fine.
You don't need anything outside of standard JDK to read from a text file easily and efficiently. For example you can do so like this:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} catch(IOException e) {
}
finally {
br.close();
}
taken from: Reading a plain text file in Java
The everything String contains the contents of the file.txt, which must be located in the same directory as where the java class file is being run from.