File Reading Error: NoSuchElementException with Scanner - java

I am relatively new to Java programming. Recently I decided to create a random system that stores, writes, and reads information on request. When reading a file I have already written with the program, I get the following errors:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at ReadFile.readFile(ReadFile.java:24)
at User.main(User.java:35)
I'm assuming this errors are a result of the User class calling on the ReadFile class, because the rest of the program works fine so far.
The User class that pertains:
import java.io.*;
import java.util.*;
public class User
{
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
Scanner user_input = new Scanner(System.in);
String input;
System.out.println("User Information System:");
System.out.println("Please type the full name of the person you wish to lookup.");
input = user_input.nextLine();
System.out.println("UIS currently has the following data on " + input + ":");
if(input.equals("First Last"))
{
System.out.println("Opening Data on " + input + "...");
}
else
{
System.out.println("No Data found.");
}
if(input.equals("/create"))
{
CreateFile create = new CreateFile();
create.openFile();
create.addRecords();
create.closeFile();
}
if(input.equals("/read"))
{
ReadFile read = new ReadFile();
read.openFile();
read.readFile();
read.closeFile();
}
}
}
As well as the ReadFile class:
import java.io.*;
import java.util.*;
public class ReadFile
{
static Scanner scanner;
public void openFile()
{
try
{
scanner = new Scanner(new File("TestFile.txt"));
}
catch(Exception e)
{
System.out.println("Error reading file.");
}
}
public void readFile()
{
while(scanner.hasNext()) //Find a way to shorten this to a loop of printing whatever is in the file.
{
String a = scanner.nextLine();
String b = scanner.next();
String c = scanner.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
scanner.close();
}
}

Related

Visitors Details question IO file handling in java

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
}
}

Java Eclipse Visitor Not Leaving Main() of test file

I'm attempting collect all the methods in a Java file using the Eclipse AST package. I believe that I have the CompilationUnit created successfully. However when I attempt to use a visitor to collect the information it doesn't go past the main() method of the file I'm testing.
public void parseCode(String fileName) {
String strSource = "";
try {
strSource = codeToString(fileName);
} catch (Exception e) {
e.printStackTrace();
}
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(strSource.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
SCTVisitor v = new SCTVisitor();
cu.accept(v);
System.out.println(v.m);
}
public class SCTVisitor extends ASTVisitor{
List<SimpleName> m = new ArrayList<SimpleName>();
SCTVisitor(){
System.out.println("What is love");
}
#Override public boolean visit(MethodInvocation node) {
this.m.add(node.getName());
return true;
}
}
This is part of the file I'm using to test:
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class WordCount {
public static void main(String[] args) {
System.out.println("Cheese");
countWordsViaGUI();
}
// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
setLookAndFeel();
try {
Scanner key = new Scanner(System.in);
do {
System.out.println("Opening GUI to choose file.");
Scanner fileScanner = new Scanner(getFile());
Stopwatch st = new Stopwatch();
st.start();
ArrayList<String> words = countWordsWithArrayList(fileScanner);
st.stop();
System.out.println("time to count: " + st);
System.out.print("Enter number of words to display: ");
int numWordsToShow = Integer.parseInt(key.nextLine());
showWords(words, numWordsToShow);
fileScanner.close();
System.out.print("Perform another count? ");
} while(key.nextLine().toLowerCase().charAt(0) == 'y');
key.close();
}
catch(FileNotFoundException e) {
System.out.println("Problem reading the data file. Exiting the program." + e);
}
}
My results are:
[println, countWordsViaGUI]
My expected results are:
[println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]
Please let me know if you have any insight into this problem.

Can't read files from command line. The files are in the same folder. FileNotFountException

I am writing this to take in data about books from a txt file. (ISBN, Price, Stock) I keep running into FileNotFoundException problems and cant figure out where the problem is. Sorry if the code is bad or whatever i'm still very now to programming.
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.File;
public class BookInventory {
static ArrayList ISBN = new ArrayList();
static ArrayList Price = new ArrayList();
static ArrayList Stock = new ArrayList();
public static void main(String[] args)throws FileNotFoundException{
if(handleArgs(args)){
for(int j = 0; j < args.length; j++){
getInventory(args, j);
}
}
}
public static void getInventory(String[]args, int j)throws FileNotFoundException{
Scanner input = null;
try {
File inputFile = new File(args[j]);
Scanner booksFile = new Scanner(inputFile);
if(booksFile.hasNextDouble()){
while (booksFile.hasNext()) {
try {
ISBN.add(booksFile.next());
Price.add(booksFile.next());
Stock.add(booksFile.next());
} catch (java.util.InputMismatchException ex) {
throw ex;
}
}
}
} catch (FileNotFoundException ex) {
System.out.println("Error: File " + args[j] + " not found. Exiting program.");
System.exit(1);
}
}
public static boolean handleArgs(String[]args){
if(args.length < 2){
System.out.println("Incorrect number of command line arguments.");
System.out.println("Program requires at least 2 files.");
return false;
}
return true;
}
}

I'm stuck building a line reader with interfaces in Java

I'm trying to make it so my program
chooses a file
reads the code one line at a time
uses an interface to do three different things
convert to uppercase
count the number of characters
save to a file ("copy.txt")
I'm stuck with the formatting parts. For instance, I'm not sure where the println commands needs to be. Any help will definitely be appreciated. I'm a beginner and still learning basic things.
Interface for Processing Individual Strings:
public interface StringProcessor
{
void process(String s);
}
Processing Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
class FileProcessor
{
private Scanner infile;
public FileProcessor(File f) throws FileNotFoundException
{
Scanner infile = new Scanner(System.in);
String line = infile.nextLine();
}
public String go(StringProcessor a)
{
a.process(line);
}
}
Driver Class:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
import javax.swing.JFileChooser;
public class Driver
{
public static void main(String[] args) throws FileNotFoundException
{
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
inputFile = chooser.getSelectedFile();
}
FileProcessor infile = new FileProcessor(inputFile);
int total=0;
}
}
This Would Make Each Line Uppercase:
public class Upper implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
System.out.println(infile.nextLine().toUpperCase());
}
}
}
This Would Count Characters:
public class Count implements StringProcessor
{
public void process(String s)
{
while (infile.hasNextLine())
{
int charactercounter = infile.nextLine().length();
total = total+charactercounter;
}
}
}
This Would Print to a File:
import java.io.PrintWriter;
import java.io.FileNotFoundException;
public class Print implements StringProcessor
{
public void process(String s)
{
PrintWriter out = new PrintWriter("copy.txt");
while (infile.hasNextLine())
{
out.println(infile.nextLine());
}
out.close();
}
}
Java was one of the first programming languages I learned and once you get it, it's so beautiful. Here is the solution for you homework, but now you have a new homework assignment. Go and figure out what is doing what and label it with notes. So next time you have a similar problem you can go over your old codes and cherry pick what you need. We were all noobs at some point so don't take it to bad.
StringProcessor.java
public interface StringProcessor {
public String Upper(String str);
public int Count(String str);
public void Save(String str, String filename);
}
FileProcessor.java
import java.io.FileWriter;
public class FileProcessor implements StringProcessor{
public FileProcessor(){
}
// Here we get passed a string and make it UpperCase
#Override
public String Upper(String str) {
return str.toUpperCase();
}
// Here we get passed a string and return the length of it
#Override
public int Count(String str) {
return str.length();
}
// Here we get a string and a file name to save it as
#Override
public void Save(String str, String filename) {
try{
FileWriter fw = new FileWriter(filename);
fw.write(str);
fw.flush();
fw.close();
}catch (Exception e){
System.err.println("Error: "+e.getMessage());
System.err.println("Error: " +e.toString());
}finally{
System.out.println ("Output file has been created: " + filename);
}
}
}
Driver.java
import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Driver {
#SuppressWarnings("resource")
public static void main(String[] args){
System.out.println("Welcome to the File Processor");
Scanner scan = new Scanner(System.in);
System.out.print("\nWould you like to begin? (yes or no): ");
String startProgram = scan.next();
if(startProgram.equalsIgnoreCase("yes")){
System.out.println("\nSelect a file.\n");
JFileChooser chooser = new JFileChooser();
File inputFile = null;
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
inputFile = new File(chooser.getSelectedFile().getAbsolutePath());
try{
Scanner file = new Scanner(inputFile);
file.useDelimiter("\n");
String data = "";
FileProcessor fp = new FileProcessor();
while (file.hasNext()){
String line = file.next();
System.out.println("Original: " +line);
System.out.println("To Upper Case: " +fp.Upper(line));
System.out.println("Count: " +fp.Count(line));
System.out.println();
data += line;
}
System.out.println("\nFile Processing complete!\n");
System.out.print("Save copy of file? (yes or no): ");
String save = scan.next();
if(save.equalsIgnoreCase("yes")){
fp.Save(data, "copy.txt");
System.out.println("\nProgram Ending... Goodbye!");
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}catch (Exception e){
e.printStackTrace();
}
}
}else{
System.out.println("\nProgram Ending... Goodbye!");
}
}
}
text.txt
some text here to test the file
and to see if it work correctly
Just a note when you save the file "copy.txt", it will show up in your project folder.
As your problem operates on streams of characters, there is already a good Java interface to implement. Actually, they are two abstract classes: FilterReader or FilterWriter — extending either one will work. Here, I've chosen to extend FilterWriter.
For example, here is an example of a Writer that keeps track of how many characters it has been asked to write:
import java.io.*;
public class CharacterCountingWriter extends FilterWriter {
private long charCount = 0;
public CharacterCountingWriter(Writer out) {
super(out);
}
public void write(int c) throws IOException {
this.charCount++;
out.write(c);
}
public void write(char[] buf, int off, int len) throws IOException {
this.charCount += len;
out.write(buf, off, len);
}
public void write(String str, int off, int len) throws IOException {
this.charCount += len;
out.write(str, off, len);
}
public void resetCharCount() {
this.charCount = 0;
}
public long getCharCount() {
return this.charCount;
}
}
Based on that model, you should be able to implement a UpperCaseFilterWriter as well.
Using those classes, here is a program that copies a file, uppercasing the text and printing the number of characters in each line as it goes.
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
try (CharacterCountingWriter ccw = new CharacterCountingWriter(new FileWriter(args[1]));
UpperCaseFilterWriter ucfw = new UpperCaseFilterWriter(ccw);
Writer pipeline = ucfw) { // pipeline is just a convenient alias
String line;
while (null != (line = in.readLine())) {
// Print count of characters in each line, excluding the line
// terminator
ccw.resetCharCount();
pipeline.write(line);
System.out.println(ccw.getCharCount());
pipeline.write(System.lineSeparator());
}
pipeline.flush();
}
}

Unable to accept filenames as arguments for reading from (or writing to) a file

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.

Categories