I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -
static Scanner input = new Scanner(System.in);
public static String readingFiles(String fileout) {
boolean find = false;
while(!find) {
try {
File f = new File(input.nextLine());
Scanner scan = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
}
}
ArrayList<String> list = new ArrayList<String>();
while (input.hasNext())
{
list.add(input.nextLine());
}
String output = list.toString();
return output;
}
It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.
Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -
case 1:
System.out.println("You chose Read File. Enter your file name: ");
System.out.println(Question4.readingFiles(input.nextLine()));
pressEnter();
break;
edit: I now have this, which works but only prints the first line of my file?
public static String readingFiles(String fileout) {
boolean find = false;
String result = "";
while (!find) {
try {
File read = new File(fileout);
Scanner check = new Scanner(read);
result = check.nextLine();
find = true;
check.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Please try again.");
break;
}
}
return result;
}
Check the following code.
public static void readFiles() throws Exception {
int i = 1;
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
while(i <= 5){
System.out.print("Enter a file name::::");
input = new Scanner(System.in);
if(input.hasNextLine()){
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null){
System.out.println(str);
}
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
fileFound = false;
i++;
continue;
} catch (IOException e) {
System.out.println("IOException");
i++;
continue;
} catch (Exception e) {
System.out.println("Some Other Exception");
i++;
continue;
} finally{
if(fileFound)
reader.close();
}
}
i++;
}
}
Please note this method will read files 5 times. If you want to change it, you can pass an int parameter to the method and accordingly change the first while condition. Ensure you give complete path of the file with escape characters. For example, if file location is 'C:\abc.txt', you need to input 'C:\\abc.txt'. Else, it will display 'File Not Found' in console.
public class readingFiles {
public static String readingFiles(String fileout) {
try {
//find a file with the same name as the value of "fileout"
File f = new File(fileout);
Scanner scan = new Scanner(f);
//create a list to hold the file output
ArrayList<String> list = new ArrayList<String>();
//loop through the output line by line and add to the list
while (scan.hasNext())
{
list.add(scan.nextLine());
}
//convert the list into a String value to pass back to the caller
String output = list.toString();
scan.close();
return output;
} catch (FileNotFoundException e) {
//if file is not found, return a value of -1
System.out.println("File Not Found.");
return("-1");
}
}
Okay a few things:
Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.
The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.
You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).
Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.
As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.
Related
I would like to replace the first line of the document Vokabeln.txt, where the number of vocabularies is stored, so that when a vocabulary is added, the number is increased by one.
Thanks for helping me.
import java.io.*;
public class Vokabeltrainer
{
private String file;
private String line;
private int anzahlVokabeln;
private boolean status = true;
Scanner sc = new Scanner(System.in);
private ArrayList <Vokabel> Vokabelliste;
public Vokabeltrainer()
{
this.file = "";
this.Vokabelliste = new ArrayList<Vokabel>();
}
public void main() throws IOException
{
System.out.println("Vokabeln.txt");
this.file = ("Vokabeln.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file)))
{
line = br.readLine();
anzahlVokabeln = Integer.parseInt(line);
for(int i = 0;i < anzahlVokabeln; i++)
{
line = br.readLine();
this.Vokabelliste.add(new Vokabel(line.split("\\s+")[0],line.split("\\s+")[1]));
}
}
while(status==true)
{
System.out.println("Was willst du machen \n-Vokabel hinzufügen\n-Vokabel enfernen\n-Vokabeln Abfragen\n-Programm Quit");
String line = sc.nextLine();
if(line.equals("one")||line.equals("Add vocabulary"))
{
Vokabelhinzufügen();
}
else if(line.equals("two")||line.equals("Remove vocabulary"))
{
}
else if(line.equals("three")||line.equals("Vokabeln Abfragen"))
{
}
else if(line.equals("four")||line.equals("Quit"))
{
status = false;
//Maybe Statistics from the User
}
else
{
System.out.println("This option doesnt exists.");
}
}
}
public void Vokabelhinzufügen()
{
boolean vokabelhinzustatus = true;
String Vokabel = "";
while(vokabelhinzustatus==true)
{
System.out.println("Please enter the vocabulary now. (Hallo Hello)");
Vokabel = sc.nextLine();
try(PrintWriter output = new PrintWriter(new FileWriter("Vokabeln.txt",true)))
{
output.printf("%s\r\n", Vokabel.toLowerCase());
String after = String.valueOf(anzahlVokabeln+1);
String before = String.valueOf(anzahlVokabeln);
//At this point the replace has to be. before is the number before the translation was added and after is after the translation was added.
}
catch (Exception e) {}
System.out.println("Vocabulary Successfully Added");
System.out.println("Exit Add Vocabulary?");
String line = sc.nextLine();
if(line.equals("yes"))
{
break;
}
}
}
public void Vokabelentfernen()
{
}
}
Not an answer to your question;
a design suggestion instead.
It appears that you have a file in which you store things
(perhaps Vokablin)
and each thing in the file is structured the same,
but contains different details.
Do not store the count in the file.
Instead,
Just store things in the file and read them all.
If you must,
add a marker at the end of the file that indicates "end of stuff".
For, reasons, you might want to store a count of things in the file.
If that is the case,
store the count as part of the end-of-file marker.
If you use this technique,
your add-to-the-file algorithm becomes this:
Read a line.
Is the line a thing?
if yes, write it,
if no, parse the end-of-file marker, increment the count, and write the end-of-file marker.
Hello so i have an assignment and my code is not working. I ask a user to input a filename and after that it freezes and does not process the number of lines. im doing something wrong but im not sure what? can someone please help me im really desperate this part is crashing my whole program and i might fail and i dont know who to ask :( for help
public static void fileReader()
{
Scanner sc = new Scanner(System.in);
int catNum;
int dogNum;
int fishNum;
String fileName;
System.out.println("Please enter the Name of the file you want to read in
from");
fileName = sc.nextLine();
System.out.println("this is the file name --> "+fileName);
catNum = TestFile.getNum(fileName, "cat");
dogNum = TestFile.getNum(fileName, "dog");
fishNum = TestFile.getNum(fileName, "fish");
System.out.println("THE CAT IS" +catNum);
System.out.println("THE DOG IS" +dogNum);
System.out.println("THE FISH IS" +fishNum);
}
i dont see anything wrong after i ask for the file name it freezes
public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try {
fileStrm = new FileInputStream (fileName);
rdr = new InputStreamReader (fileStrm);
bufRdr = new BufferedReader (rdr);
line = bufRdr.readLine();
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
fileStrm.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch(IOException ex2)
{
System.out.println("This is Error");
}
}
System.out.println("error reading file !!" +e.getMessage());
}
return lineNum; }
the file looks something like this (each line is like this):
CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016
Look at this while loop:
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
If firstWord.equalsIgnoreCase(word) returns false, then what will happen? The value of line will never be updated and the loop will never exit.
I'm trying to write a do while loop that will read a file that the user input and read it out and will loop until the user types end. The do part is working, but my while just isn't being activated and I'm struggling to figure out why.
public static void readingFiles() throws Exception {
BufferedReader reader = null;
Scanner input = null;
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
input = new Scanner(System.in);
if(input.hasNextLine())
{
try {
File f = new File(input.nextLine());
reader = new BufferedReader(new FileReader(f));
String str = null;
while((str = reader.readLine()) != null)
{
System.out.println(str);
}
}
catch (FileNotFoundException e)
{
System.out.println("File Not Found. Please try again.");
fileFound = false;
continue;
}
catch (IOException e)
{
System.out.println("There was an IOException. Please try again.");
continue;
}
catch (Exception e)
{
System.out.println("There was an exception. Please try again.");
continue;
}
finally
{
{
if(fileFound)
reader.close();
}
}
}
} while(!input.nextLine().equalsIgnoreCase("end"));
}
I've tried using an if statement before my input.hasNextLine() but then it would ignore the rest of the whole program and do nothing and only typing end would work. I've tried using && in my current if statement too but that didn't work. And I tried using a boolean that I set to true if string contained end. I think the problem may be in the input.hasNextLine but I'm not sure why or what to change it to?
Thanks for any help
Calling input.nextLine() again will not preserve your previous input string.
Store it in a variable, and compare that
public static void readingFiles() throws Exception {
BufferedReader reader = null;
String filename = null;
Scanner input = new Scanner(System.in);
boolean fileFound = true;
do {
System.out.print("Enter a file name or Type END to exit: ");
if(input.hasNextLine()) {
filename = input.nextLine();
try {
File f = new File(filename);
// reader =
...
} while (!filename.equalsIgnoreCase("end");
I cannot seem to figure out a problem. here is what I'm trying to do open and read the content of a .txt file. If there is a problem with one of the lines of data in the file skip it and continue reading the file
I cannot find a method to skip the line that does not contain a valid value and continue to read the file. Here is my code.
int theValue = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String value = input.next();
theValue = Integer.parseInt(value);
}
input.close();
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
thanks for all the help in advance.
Well, maybe not the best idea, but a simple solution would be to encapsulate parseInt in a try/catch:
int theValue = 0;
try {
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String value = input.next();
try{
theValue = Integer.parseInt(value);
}catch (Exception e){
//Just ignore it and carry on.
}
}
input.close();
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters