What does this error mean? On every line of the code below the try catch block this error occurs. I'm confused as to why this error keeps appearing.
My imports:
import java.util.*;
import java.io.*;
My method:
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)
{
Scanner list1s;
Scanner list2s;
try
{
list1s = new Scanner(new File("list1.txt"));
list2s = new Scanner(new File ("list2.txt"));
}
catch(FileNotFoundException ex)
{
System.out.println("File not found!\n");
}
while(list1s.hasNext())
list1.add(list1s.next());
while(list2s.hasNext())
list2.add(list2s.next());
list1s.close();
list2s.close();
}
Updated code was from the suggestions in the comments. However, I get the following error: variable list1s might not have been initialized
while(list1s.hasNext())
If I do not have the scanner declaration and initialization in the try/catch. Any idea as to why this is happening?
static Scanner list1s;
static Scanner list2s;
public static void readLists(ArrayList <String> list1, ArrayList <String> list2)
{
try
{
list1s = new Scanner(new File("list1.txt"));
list2s = new Scanner(new File ("list2.txt"));
}
catch(FileNotFoundException ex)
{
System.out.println("File not found!\n");
}
// Your code
}
Just for reference: class and instance variables when declared, are automatically given their default values.
Related
VIP group of companies introduce a new shopping mall “Le Le” . To promote the mall they had approached “6th Event” a famous commercial event organizer to organize an event of lucky draw. The organizer has to collect name, phone and email id of all the visitors during promotion time and give it to the company.
The organizer needs an automated application and wants to store records in a text file called “visitors.txt”.
Records should to be stored in the following structure
Name1,phonenumber1,emailId1;Name2,phonenumber2,emailId2;
In a record, each attributes should be separated using comma (,) and records should be separated using semi colon (;).
Create a Java Application which has two classes called Main.java and FileManager.java
In FileManager class implement the following methods [method skeletons are given]
static public File createFile() – This method should create the file and return it.
static public void writeFile(File f, String record) – In the method, first parameter is the file reference in which records to be added and second parameter is a record, This record should append in the file. [Record should be as per the given format]
static public String[] readFile(File f) – This method accept file to be read, returns all records in the file.
[Note : Don’t modify the signature of the given methods]
In Main class use the following Input and Output statements and call the needed methods from FileManager class to manipulate files.
Enter Name
John
Enter Phone Number
1234567
Enter Email
johnpeter#abc.com
Do you want to enter another record(yes/no)
yes
Enter Name
Grace
Enter Phone Number
98765412
Enter Email
gracepaul#xyz.com
Do you want to enter another record(yes/no)
no
Do you want to display all records(yes/no)
yes
John,1234567,johnpeter#abc.com
Grace,98765412,gracepaul#xyz.com
FileManager class
//import necessary packages
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File file =new File("visitors.txt");
try{ file.createNewFile();}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return file;
}
//change the return type as per the requirement
static public void writeFile(File f, String record)
{ try {
BufferedWriter out = new BufferedWriter(
new FileWriter(f.getName(), true));
out.write(record+";");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
static public String[] readFile(File f)
{
List<String> tokens = new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
// String [] arr= myReader.nextLine().split(";");
// tokens = Arrays.asList(arr);
tokens.add(myReader.nextLine());
}
myReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
String[] tokenArray = tokens.toArray(new String[0]);
//=tokenArray.split(";");
return tokenArray;
}
}
Main class
import java.util.*;
import java.io.FileNotFoundException;
//import necessary packages
import java.io.File;
#SuppressWarnings("unchecked")//Do not delete this line
public class Main
{
public void abcd(){
Scanner in = new Scanner(System.in);
System.out.println("Enter Name");
String name=in.next();
System.out.println("Enter Phone Number");
long phone=in.nextLong();
System.out.println("Enter Email");
String id= in.next();
FileManager f= new FileManager();
File x =f.createFile();
f.writeFile(x,name+","+phone+","+id);
System.out.println("Do you want to enter another record(yes/no)");
String choice=in.next();
if(choice.equals("yes")){
abcd();
}
if(choice.equals("no"))
{String []q=f.readFile(x);
String pl[]=q[0].split(";");
for(int i=0;i<pl.length;i++)
{
System.out.println(pl[i]);
}
System.exit(0);
}
}
public static void main(String[] args)
{
Main asd=new Main();
asd.abcd();
}
}
This program gives me desired output but not able to run all test cases.
Getting error could not append multiple files. Dont know is this.But it works perfectly on compiler. And you should at least try to code rather then simply asking someone to code.
//all test case passed
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File myObj = new File("visitors.txt");
try{
if(new File("visitors.txt").isFile()==false)
myObj.createNewFile();
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return myObj;//change the return type as per the requirement
}
static public void writeFile (File f, String record)
{
try
{
FileWriter fw = new FileWriter(f.getName(),true); //the true will append the new data
fw.write(record+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
static public String[] readFile(File f)
{
List<String> list=new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String str=myReader.nextLine();
String[] parts = str.split(";");
for (String part : parts) {
list.add(part);
}
}
myReader.close();
}
catch(FileNotFoundException ex){}
String[] strings = list.stream().toArray(String[]::new);
return strings;
//change the return type as per the requirement
}
}
Can anyone tell me why I have this error: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement.
I try to save text from a file in an ArrayList.
import java.io.*;
import java.util.*;
public class EditMembership
{
public static void main(String[] args) throws java.io.FileNotFoundException
{
ArrayList<String> member = readFromFile("database.txt");
System.out.println(Arrays.toString(member.toArray()));
}
public static ArrayList readFromFile(String fileName) throws java.io.FileNotFoundException
{
Scanner x = new Scanner(new File(fileName));
ArrayList<String> memberList = new ArrayList<String>();
try {
while (x.hasNextLine())
{
memberList.add(x.nextLine());
}
x.close();
}
catch(FileNotFoundException e)//here is the error
{
e.printStackTrace();
}
return memberList;
}
}
Because you aren't doing anything to open a file within the try block it's impossible to throw a File Not Found. Move the Scanner declaration down within the try block and I would expect that'll fix it. At that point you can remove the "throws" declaration from your method signature.
On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.
This question already has answers here:
Why is "throws Exception" necessary when calling a function?
(8 answers)
Closed 8 years ago.
Why am I getting a "must be caught or declared to be thrown" error with this code ? All I want is to test a bunch of code by pasting it into a new java program what is the easiest way to bunch of code ?
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
for (String symb : symbolList) {
System.out.println(symb);
}
logput.close();
}
}
Some of the methods you're calling can throw FileNotFoundException if the file isn't found:
public Scanner(File source) throws FileNotFoundException
public PrintWriter(String fileName) throws FileNotFoundException
Java's compiler checks that some thrown exceptions -- those other than RuntimeException and its subclasses -- are either caught or declared thrown. Compilation will fail otherwise. This helps find some errors at compile-time, before the program is ever run.
One option is to declare your calling function to throw the exception or a superclass:
public static void main(String[] args) throws FileNotFoundException {
A better option in this case is to catch the exception and do something with it. For example, here's how you can do that for the Scanner() exception:
File inFile = new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt");
try {
Scanner sc = new Scanner( inFile );
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
}
catch ( FileNotFoundException e ) {
System.out.println("Could not find file: " + inFile.getAbsolutePath());
}
Your two Scanner declaration lines have a chance to throw an exception, which are basically errors that happen after the code is executed (because of this they are sometimes called runtime errors). Because the compiler knows that your code might make a FileNotFoundException happen, it requires you to catch the exception.
This is done by enclosing the code in a try-catch block.
try {
Scanner sc = new Scanner(new File("C:\\Users\\User\\Selenium\\scrapjv\\interface\\NASDAQlist.txt"));
List<String> symbolList = new ArrayList<String>();
while (sc.hasNextLine()) {
symbolList.add(sc.nextLine());
}
PrintWriter logput = new PrintWriter("C:\\Users\\User\\Selenium\\scrapjv\\interface\\log.txt", "UTF-8");
for (String symb : symbolList) {
System.out.println(symb);
}
logput.close();
} catch (java.io.FileNotFoundException ex)
{
ex.printStackTrace();
}
The following program is meant to read from a file:-
import java.util.*;
import java.io.*;
import java.lang.*;
public class file_read
{
private Scanner input = new Scanner(System.in);
private Scanner fileinput;
public void open() // [1]
{
try
{
String filename = input.next();
fileinput = new Scanner(new File(filename+".txt")); // [2]
}
catch(Exception e)
{
System.out.println("opening error.");
}
}
public void read()
{
// some task to read the file
}
public void closeFile()
{
// closing the file
}
}
Problem lies with [1] and I think that the statement [2] is creating the problem. If I replace the filename+".txt" with the actual filename, everything runs fine. I am unable to pinpoint the reason. Please help.