Java exception from scanning a file that was imported - java

I am trying to make a program that imports a text file and analyzes it to tell me if another text file has possible match up sentences. I keep running into this error when I import my file and attempt to analyze it. I am assuming that I am missing something in my code.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at PossibleSentence.main(PossibleSentence.java:30)
Heres my code too:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PossibleSentence {
public static void main(String[] args) throws FileNotFoundException{
Scanner testScan = new Scanner(System.in);
System.out.print("Please enter the log file to analyze: ");
String fileName = testScan.nextLine();
File f = new File(fileName);
Scanner scan = new Scanner(f);
String line = null;
int i = 0;
while (scan.hasNextLine()) {
String word = scan.next();
i++;
}
scan.close();
File comparative = new File("IdentifyWords.java");
Scanner compare = new Scanner(comparative);
String line2 = null;
}
}
The second scanner I havent completed yet either. Any suggestions?

We need more info to conclusively answer, but check out the documentation for next(). It throws this exception when there's no next element. My guess is it's because of this part:
String fileName = testScan.nextLine();
You're not checking if hasNextLine first.

You are passing a file argument to a Scanner object, try using an InputStream
File input = new File(/* file argument*/);
BufferedReader br = null;
FileReader fr= null;
Scanner scan = null;
try {
fr = new FileReader(input);
br = new BufferedReader(fr);
scan = new Scanner(br);
/* Do logic with scanner */
} catch (IOException e) {
/* handling for errors*/
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
if (scan != null) {
scan.close();
}
} catch (IOException e) {
/* handle closing error */
}
}

Related

Proper method for a try, catch, and finally for Scanner and BufferedReader

Trying to understand the best and most efficient way for a try-catch-finally for both the Scanner and BufferedReader in my main method. Should there be two different catches or combine them into one?
public static void main(String[] args) throws IOException {
//open file input stream
try {
BufferedReader reader = new BufferedReader(new FileReader("DATABASE.txt"));
//read file line by line
String line = null;
Scanner scan = null;
BST tree = new BST();
line = reader.readLine();
while(line != null) {
Employee emp = new Employee();
scan = new Scanner(line);
scan.useDelimiter(",");
while(scan.hasNext()){
emp.setEmployeeID(Integer.parseInt(scan.next()));
emp.setFirstName(scan.next());
emp.setLastName(scan.next());
emp.setSalary(Double.parseDouble(scan.next()));
line = reader.readLine();
}
tree.insert(emp);
}
reader.close();
tree.inOrder();
//System.out.println(empList);
} catch(IOException e){
e.printStackTrace();
}
A single catch block should be sufficient. You can add a finally block that will close the reader and scanner instances (if they are non null). This way, they will be closed regardless if the try block finishes normally or an exception is thrown. The null checks should be added because the try block might not reach the initialization of both objects, as an exception might occur.
Declared Scanner scan = null and BufferedReader reader = null; outside of the try-catch-finally block of code and initialized them inside the try block. The exception gets caught and they both reach the finally block.
public static void main(String[] args) throws IOException {
Scanner scan = null;
BufferedReader reader = null;
//open file input stream
try {
reader = new BufferedReader(new FileReader("DATABASE.txt"));
//read file line by line
String line = null;
Scanner scan = null;
BST tree = new BST();
line = reader.readLine();
scan = new Scanner(line);
while (line != null) {
Employee emp = new Employee();
scan.useDelimiter(",");
while (scan.hasNext()) {
emp.setEmployeeID(Integer.parseInt(scan.next()));
emp.setFirstName(scan.next());
emp.setLastName(scan.next());
emp.setSalary(Double.parseDouble(scan.next()));
line = reader.readLine();
}
tree.insert(emp);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
scan.close();
}
}
You do not need to use both BufferedReader and Scanner. One Scanner is enough:
public static BST readFile(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useLocale(Locale.US); // mandatory for read double values
BST bst = new BST();
while (scan.hasNext()) {
Employee employee = new Employee();
employee.setEmployeeID(scan.nextInt());
employee.setFirstName(scan.next());
employee.setLastName(scan.next());
employee.setSalary(scan.nextDouble());
bst.insert(employee);
}
bst.inOrder();
return bst;
}
}

Do-while loop not paying attention to the while in java

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");

Cannot find symbol when using bufferwriter.readline()

I'm trying to learn java but I don't know why I'm getting there errors.What I basically want is that user will input new characters and will be written to the file as long it is not the word "stop"(program terminates at this point).
Can you guys help me?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
You are trying to read from writer which you can't. You already have scanner and using it, you could read form System input i.e. Keyboard.
Change your line like:
From
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
To
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
You are trying to read from your output, not your input
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}

Java - I want to read a file name from command line then use a bufferedreader to read each line

I'm getting an eclipse red underline error on the
br = new BufferedReader(new FileReader(inFile));
line on "inFile". This is the object that I would like to read which I believe contains the command line filename/path that I give it on the command line. Am I handling this wrong?
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (0 < args.length) {
File inFile = new File(args[0]);
}
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(inFile));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Change this:
if (0 < args.length) {
File inFile = new File(args[0]);
}
to this:
File inFile = null;
if (0 < args.length) {
inFile = new File(args[0]);
} else {
System.err.println("Invalid arguments count:" + args.length);
System.exit();
}
because the file variable is not accessible outside the if/else statement.
I've added in the else (for the case when no args are provided) a friendly message saying the the argument count was invalid and exit for the program.
inFile is declared in the if statement. As such, it's scope ends at line 11;
Your variable, inFile, is local to the containing if-block.
Perhaps this:
public static void main(String[] args) {
File inFile = null;
if (0 < args.length) {
inFile = new File(args[0]);
}
The variable inFile loses scope outside of the if block:
if (0 < args.length) {
File inFile = new File(args[0]);
}
Change to:
File inFile = null;
if (0 < args.length) {
inFile = new File(args[0]);
// Make sure the file exists, can read, etc...
}
else
{
// Do something if a required parameter is not provided...
}
After the 'if' statement block, you could dump contents of "inFile" to a Scanner object.
Scanner scannedIn = new Scanner(inFile);
Then use the '.next' method to verify that you're accessing the file.
System.out.println(scannedIn.next());

Read data from a text file using Java

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}

Categories