Can someone please help me determine what I am doing wrong with my code. I am getting a stackoverflow error. At the end of my code I am using recursion and I don't have a base case to stop the program. It keeps looping and displaying my text file until I get a stackoverflow error.
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Joseph\\Documents\\School Files - NHCC\\CSci 2002\\FinalQuestionBank_JosephKraemer.txt"); //file location
try
{
Scanner scan = new Scanner(textFile); //Scanner to import file
while(scan.hasNextLine()) //Iterator - while file has next line
{
String qBank = scan.nextLine(); //Iterator next line
String[] tempArray = qBank.split("::"); //split data via double colon
System.out.println(qBank); //print data line
}
scan.close(); //close scanner
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return readFinalQuestionBank(); //use of Recursion
}//end method readFinalQuestionBank
}//end class Reader
if your main objective is to read the whole input file by implementing recursivity take a look at the following example, it replaces the while statement with a recursive method call.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Reader
{
public static String readFinalQuestionBank() throws Exception
{
File textFile = new File("C:\\Users\\Diego\\Documents\\sandbox\\input.txt");
String output = "";
try
{
Scanner scan = new Scanner(textFile);
output = readLineRecursively(scan);
scan.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
return output;
}
private static String readLineRecursively(Scanner scan){
if(!scan.hasNextLine()){
return "";
}
String qBank = scan.nextLine();
return qBank + "\n" + readLineRecursively(scan);
}
public static void main(String[] args){
try {
System.out.println(readFinalQuestionBank());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I know there are many questions related to this, but I still do not follow. I have copied the below code from a tutorial on how to create, write to and read from a file. There is a CreateFile class, a ReadFile class and a Demo class:
CreateFile.java
import java.io.*;
import java.lang.*;
import java.util.*;
public class CreateFile {
private Formatter x;
public void openFile(){
try{
x = new Formatter("chinese.txt");
}
catch(Exception e)
{
System.out.println("You have an error");
}
}
public void addRecords(){
x .format("%s%s%s", "20 ", "bucky ", "robers");
}
public void closeFile(){
x.close();
}
}
ReadFile.java
public class ReadFile {
private Scanner x;
public void openFile()
{
try{
x = new Scanner(new File("words.txt"));
}
catch(Exception e){
System.out.println("could not find file");
}
}
public void readFile()
{
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s\n", a,b,c);
}
}
public void closeFile()
{
x.close();
}
}
public class Demo {
public static void main(String[] args) {
CreateFile g = new CreateFile();
g.openFile();
g.addRecords();
g.closeFile();
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
}
In Demo.java if I remove the last four statements related to reading the file, the first four statements related to opening and writing to a file run without error. However, once I add
WordCounter r = new WordCounter();
r.openFile();
r.readFile();
r.closeFile();
and run the program, it outputs: Exception in thread "main" could not find file. I am not sure what is going on, is the file chinese.txt never being created?
I'd suggest that you look into serialization it much easier and simpler than writing to .txt files.
But if you really need to do .txt files this is how you write to a .txt file
//This gets your project directory
private String projectPath = System.getProperty("user.dir");
//call save()
String save("test.txt", "This is will be save to a test.txt file");
private boolean save(String textfile String outputtext){
String filepath = projectPath + textfile;
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(filepath));
writer.write(outputtext);
writer.close();
} catch(IOException e) { }
return true;
}
And this is how you read it
private String load(String textfile){
String temp="";
String filepath = projectPath + textfile;
try{
BufferedReader reader =new BufferedReader(new FileReader(filepath));
while(true){
//this will read one line at a time you can append it output
try {
temp+= reader.readLine();
//If no more lines break out of the loop
if(line==null)
break;
}catch(IOException e){}
}
reader.close();
}
catch(IOException e){}
//Return contents of the file you loaded
return temp;
}
I hope that this code is clear enough. If you have any further questions let me know. I'll gladly answer them.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static Scanner userScanner = new Scanner(System.in);
public static void main(String[] args) {
Scanner fileScanner = openInputFile();
if (fileScanner == null)
return;
fileScanner.nextLine();
while(fileScanner.hasNextLine()){
//handle input
}
fileScanner.close();
}
public static Scanner openInputFile() {
String filename;
Scanner scanner = null;
System.out.print("Enter the input filename: ");
filename = userScanner.nextLine();
File file = new File(filename);
try {
scanner = new Scanner(file);
} // end try
catch (FileNotFoundException fe) {
System.out.println("Can't open input file\n");
return null; // array of 0 elements
} // end catch
return scanner;
} // end openInputFile
}
I'm trying to open an input file using the following method but it prints "Can't open input file" every time. I double checked the spelling, the file is in the same directory. Am I doing anything wrong?
I have this written so far, I am just doing a few practice codes from my text book. I cant seem to get this to read the first line in my .txt .
/**
*
*/
import java.util.Scanner; //needed for scanner class
import java.io.*; //needed for File I/O classes
/**
* #author Megan
*
*/
public class Pres {
/**
* #param args
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of file: C:/User/Frances/Documents/USPres.txt");
String filename = keyboard.nextLine();
File file = new File("C:/User/Frances/Documents/USPres.txt");
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
System.out.println("The first line in the file is: ");
System.out.println(line);
inputFile.close();
}
}
I believe it has to do with this portion of the code:
String line = inputFile.nextLine();
I am not quite sure what to type into the (), if I should type anything at all. I could be wrong. My textbook isn't to clear about the proper format. If you could help, please and thank you. :)
To read txt file do this:
String line = "";
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(fileName));
while ((line = in.readLine()) != null) {
// do something here
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It will read all lines in the text but since it's practice go ahead and try to figure out how to read just one line.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Pres {
public static void main(String[] args) throws FileNotFoundException, IOException {
// BufferedReader is best for read line from file or else
BufferedReader Bfr = new BufferedReader(new FileReader("your_filename_or_path.txt"));
// get first line from file
String firstLinetext = Bfr .readLine();
System.out.println(firstLinetext ); // print first line
}
}
How would I go about making my program terminate once it reaches a specific word from a file. So far, I have it printing out all the words from the file which I want. "input" contains the words "one two three four galumph" just like that.
import java.util.Scanner;
import java.io.*;
class EchoWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("input"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (sc2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
}
}
I have written the following very simple Java program to ask user enter a file name, then it will report the number of lines of this file to the standard output:
import java.io.*;
import java.util.*;
public class CountLine {
public static void main(String[] args)
{
// prompt the user to enter their file name
System.out.print("Please enter your file name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
fileName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the file name, " + fileName);
File file = new File("C:/Users/Will/Desktop/"+fileName);
Scanner scanner;
try {
scanner = new Scanner(file);
int count =0;
String currentLine;
while(scanner.hasNextLine())
{
currentLine=scanner.nextLine();
count++;
}
System.out.println("The number of lines in this file is "+count);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("There is no such file");
e.printStackTrace();
}
}
}
It is working.I would be really thankful if experts could help me
see if there is anything that can be improved in this code fragment,
If the file is not found, the exception is caught in the outermost catch statement and print out the stack trace. However, I think it is not very user-friendly, is there a way if the file does not exist, then the whole process restarts from beginning?
Thanks in advance.
Get some Structure in your code:
public static void main(String[] args)
{
string output;
string fname = readFileName();
if (fileValid(fname)) //Ensure FileExists
{
int lineCount = scaneFile(fname);
output = "some output text including line numbers"
}
else
{
output = "File Not Valid..."
}
//showOutput...
}
Obvious change is to make a method countLines(String filename) that contains most of the code currently in main(). Obviously main() will call countLines().
Prompting for a file could live in main() or another method.
To restart on error you need a loop like:
filename = // read filename from stdin;
while(keepGoing(filename)) { // null check or whatever to let you out of the loop
try {
int numLines = countLines(filename);
println("num lines in " + filename + "=" +numLines);
}
catch(Exception ex) { // or just specific excpetions
ex.printStackTrace();
}
}
Unless you want to make a GUI. I suggest you receive the path to the file as a command line parameter.
If file doesn't exist print a message and exit. That's all.
The command line will give the user the option to move up with the up-key, edit the name and run again.
This class is named LineCounter and is the "business logic"
package countlines;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
private int lineCount = 0;
public LineCounter(File file) throws IOException{
BufferedReader inFile = new BufferedReader(new FileReader(file));
while(inFile.readLine() != null) {
lineCount++;
}
inFile.close();
}
public int getLineCount() {
return lineCount;
}
}
This class is the "presentation logic"
package countlines;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main (String[] args){
if (args.length != 1){
System.out.println("Usage: java countlines/Main filePath");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()){
System.out.println("File "+f.getAbsolutePath()+" doesn't exist");
System.exit(2);
}
if (f.isDirectory()){
System.out.println(f.getAbsolutePath()+" is a directory");
System.exit(2);
}
LineCounter c;
try {
c = new LineCounter(f);
System.out.println(c.getLineCount());
} catch (IOException e) {
System.out.println("Error reading file " + f.getAbsolutePath());
}
}
}