I need to try count the number of lines in a file while using "try" and "catch". This is what I have so far. Hoping I could get some help. It just keeps timing out.
public class LineCount {
public static void main(String[] args) {
try {
Scanner in = new Scanner(new FileReader("data.txt"));
int count = 0;
//String line;
//line = in.readLine();
while (in.hasNextLine()) {
count++;
}
System.out.println("Number of lines: " + count);
}catch (Exception e){e.printStackTrace();}
}
}
Seems like you are doing everything but consuming the newline character. To do this with java.util.Scanner, simply run in.nextLine() in your while loop. This Scanner.nextLine() method will return all characters before the next newline and consume the newline character itself.
Another thing to consider with your code is resource management. After opening the Scanner, it should be closed when it'll no longer be read. This can be done with in.close() at the end of your program. Another way to accomplish this is to setup a try-with-resources block. To do this, just move your Scanner declaration like this:
try (Scanner in = new Scanner(new FileReader("data.txt"))) {
Regarding the need for the try-catch block, as part of the Java compilation process, checked-exceptions will be checked if they are caught or thrown from a method. Checked-exceptions are everything that are not RuntimeExceptions or Errors.
It times out because you do not advance the Scanner. If you enter the while loop you will never exit it.
Also it would be better if you use BufferedReader as is is faster than a standard Scanner. Although if the file is small, maybe for readability purposes you do not. But this is up to you. Anyway.
Here you go:
//this is the try-with-resources syntax
//closing the autoclosable resources when try catch is over
try (BufferedReader reader = new BufferedReader(new FileReader("FileName"))){
int count = 0;
while( reader.readLine() != null){
count++;
}
System.out.println("The file has " + count + " lines");
}catch(IOException e){
System.out.println("File was not found");
//or you can print -1;
}
Probably your questiong has already been answered and you should not ask already answered questions before you search, for a while at least.
Related
I am sorry if this question is already answered on the internet but by looking at the 'similar questions' I couldn't find an answer for my problem.
So basically I'm trying to understand why using PrintWriter to write lines of text into a file apparently skips the first line every 2 lines I give.
This is the method I use in its own class:
public class IO_Utilities {
public static void Write(String outputName){
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(outputName);
} catch (FileNotFoundException e) {
System.out.println(e.toString());
System.exit(0);
}
System.out.println("Write your text:");
Scanner user = new Scanner(System.in);
while(!user.nextLine().equals("stop")) {
String line = user.nextLine();
outputStream.println(line);
}
outputStream.close();
user.close();
System.out.println("File has been written.");
}
When I call it from main with:
IO_Utilities.Write("output.txt");
and write:
first line
second line
third line
stop
stop
The output text is actually:
second line
stop
I am sure the problem is the while loop, because if I input the lines manually one by one it works correctly, but I don't understand exactly why it behaves like it does right now.
while(!user.nextLine().equals("stop")) {
String line = user.nextLine();
outputStream.println(line);
}
You repeat your user.nextLine(); within your loop, so line is not the same as the one you compare to "stop".
Rewrite that part as:
String line = user.nextLine();
while( !line.equals("stop")) {
outputStream.println(line);
line = user.nextLine();
}
I am not sure while am receiving a no such element exception. It seems to be an issue with the scanner not reading my file correctly, but I am not sure where I am going wrong.
I am reading a file, then using the scanner to go line by line. But I get unusual behavior, such as missing lines or filenotfound exceptions when I try to do it.
public static void readMylifeLikeABook(String fileName,int maxItems) {
// Read file line by line with different elements on each line
int bookCount=0;
int movieCount = 0;
Book [] bookItem =new Book[maxItems];
Movie [] movieItem =new Movie[maxItems];
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
Scanner line;
while (scanner.hasNext() && ((bookCount+movieCount)<maxItems)) {
line = new Scanner(scanner.nextLine()); // scan next line
if (line.next().contains("Movie")){
movieItem[movieCount]= new Movie();
movieItem[movieCount].setMediaType("Movie");
movieItem[movieCount].setTitle(scanner.nextLine());
movieItem[movieCount].setRef(scanner.nextLine());
movieItem[movieCount].setPrice(Double.valueOf(scanner.nextLine()));
movieItem[movieCount].setDirector(scanner.nextLine());
movieItem[movieCount].setActor(scanner.nextLine());
System.out.println(movieItem[movieCount].getTitle());
movieCount++;
line.close(); // close line
}
else if (scanner.next().contains("Book")){
bookItem[bookCount]= new Book();
bookItem[bookCount].setMediaType("Book");
bookItem[bookCount].setTitle(scanner.nextLine());
bookItem[bookCount].setRef(scanner.nextLine());
bookItem[bookCount].setPrice(Double.valueOf(scanner.nextLine()));
bookItem[bookCount].setAuthor(scanner.nextLine());
System.out.println(bookItem[bookCount].getTitle());
bookCount++;
line.close(); // close line
}
}
scanner.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
//System.out.println(count);
for (int i=0;i<(bookCount+movieCount);i++) {
System.out.println(bookItem[i] +"\n\n "+ movieItem[i]);
}
}
Hmm, is it possible if you can provide the file being read? This can very well be a problem with that File as if the Scanner object does not a following line to be read, it will throw an exception. Make sure the file has the needed amount of lines.
You call line.next() immediately after constructing line. Do you need to do this? If so, perhaps you need to call hasNext() first to ensure there's a token there.
(I'm pretty sure line.next() throws a NoSuchElementException if there's no token.)
Also, check your code against the file format. Are there blank lines in your file?
I need to be able to read each line of the file for multiple arguments, hence the for loop. After the first one, it does not seem to be reading them anymore, seems to skip the try statement. Any ideas? I'm sure Its something silly I am missing but have been playing about with it and unfortunately time is not on my side.
for (int j = 0; j < ags.length; j++){
try{
String nameFromFile = null;
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
while ((nameFromFile = InputReader.readLine()) != null) {
// Do stuff
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
You appear to have two sources you want to compare System.in and args I suggest you read these individually and then compare them.
Set<String> fromInt = new HashSet<>();
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
for(String line; (line = br.readLine()) != null;)
fromIn.add(normalise(line));
}
// compare argsList with fromIn.
e.g.
for(String arg: args) {
if (fromIn.contains(normalise(arg))) {
// something
} else {
// something else
}
}
I need to be able to read each line of the file
What file? You're reading from System.in:
BufferedReader InputReader = new BufferedReader(new InputStreamReader(System.in));
Your code will block at this line until you enter something at the console.
You do not read a file, bu the System.in stream.
Every stream has an internal pointer, so the stream nows, which line was read at last.
If the System stream was read once, the pointer is pointing to the end of the stream.
As long as the stream is not reset, the read command will not return anything.
try
InputStream.reset()
or even better, only read the Stream once and cache the result! This is faster and safe, because the Stream input can change during iteration.
Your code will never exit from while loop.
while ((nameFromFile = InputReader.readLine()) != null)
In above loop it will print only one time and at the end of the file it will not be out of the while loop . That's why you are getting only one time output. Since it is not exited from while loop it does not go back into for loop. readLine() return the string and it is terminated by "\n" or "\r\n". Change as below and you will be able to read as ags.length
while ((nameFromFile = InputReader.readLine())=="\n")
I've made a GUI and a button.
My code looks like this:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt contains the following text:
What do I contribute with when working in team work:
a. I come up with new ideas
b. I follow-up on things because I'm basically
thorough
c. I assess what is realistic and workable
d. I advocate alternative approaches objectively and unbiased
When trying to run I get "Some error No line found"
I tried removing all special characters from the text and I could read it, so I tried adding "UTF-8" to my scanner in this manner.
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
However this does not seem to do anything. I still get "No line found".
If this question has been asked before excuse me, I did a thorough search, but I either could not comprehend the question asked or the answer provided in context to my problem.
I changed my scanner to bufferedreader per Troubleshoot and Harshas example and it will now read the text even with special chars, however it won't display them correctly. I just get square boxes. It's a minor problem.
If persontest.txt is in classpath (i.e. inside jar or source folder) you can use:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
First of all, make sure persontest.txt is in your main project folder, and not a sub-folder of that, as it will not find it otherwise.
I recommend using a BufferedReader to read it line by line. Here's how:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
It's good practice to check that the line isn't empty along with checking it isn't equal to null. For example, if a line was equal to \t it would be classed as empty, but not as null.
You could simply do this using
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if you need to do it with a Scanner you can try using
Scanner reader = new Scanner(new FileInputStream("persontest.txt");
I tried to do counting lines, words, character from user "inputted" file.
After this show counting and keep asking again.
If file doesn't exist print all data which have been counted during running.
Code:
public class KeepAskingApp {
private static int lines;
private static int words;
private static int chars;
public static void main(String[] args) {
boolean done = false;
//counters
int charsCount = 0, wordsCount = 0, linesCount = 0;
Scanner in = null;
Scanner scanner = null;
while (!done) {
try {
in = new Scanner(System.in);
System.out.print("Enter a (next) file name: ");
String input = in.nextLine();
scanner = new Scanner(new File(input));
while(scanner.hasNextLine()) {
lines += linesCount++;
Scanner lineScanner = new Scanner(scanner.nextLine());
lineScanner.useDelimiter(" ");
while(lineScanner.hasNext()) {
words += wordsCount++;
chars += charsCount += lineScanner.next().length();
}
System.out.printf("# of chars: %d\n# of words: %d\n# of lines: ",
charsCount, wordsCount, charsCount);
lineScanner.close();
}
scanner.close();
in.close();
} catch (FileNotFoundException e) {
System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
}
}
}
But I can't understand why it always show output with no parameters:
All lines: 0
All words: 0
All chars: 0
The end
Why it omits all internal part.
It may be coz I'm using few scanners, but all look ok.
Any suggestions?
UPDATE:
Thanks all who give some hint. I rethinking all constructed and rewrite code with newly info.
To awoid tricky scanner input line, I used JFileChooser:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class KeepAskingApp {
private static int lines;
private static int words;
private static int chars;
public static void main(String[] args) {
boolean done = false;
// counters
int charsCount = 0, wordsCount = 0, linesCount = 0;
Scanner in = null;
Scanner lineScanner = null;
File selectedFile = null;
while (!done) {
try {
try {
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
while (in.hasNextLine()) {
linesCount++;
lineScanner = new Scanner(in.nextLine());
lineScanner.useDelimiter(" ");
while (lineScanner.hasNext()) {
wordsCount++;
charsCount += lineScanner.next().length();
}
}
System.out.printf(
"# of chars: %d\n# of words: %d\n# of lines: %d\n",
charsCount, wordsCount, linesCount);
lineScanner.close();
lines += linesCount;
words += wordsCount;
chars += charsCount;
in.close();
} finally {
System.out.printf(
"\nAll lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
} catch (FileNotFoundException e) {
System.out.println("Error! File not found.");
}
}
}
}
Couple of issues (actually there are many issues with your code, but I will address the ones directly related to the output you have posted):
First of all, the stuff in the catch block only happens if you get a FileNotFoundException; that's there to handle and recover from errors. I suspect you meant to put a finally block there, or you meant to do that after the catch. I suggest reading this tutorial on catching and handling exceptions, which straightforwardly describes try, catch, and finally.
Once you read that tutorial, come back to your code; you may find that you have a little bit of reorganizing to do.
Second, with the above in mind, it's obvious by the output you are seeing that you are executing the code in that catch block, which means you are getting a FileNotFoundException. This would be caused by one of two (possibly obvious) things:
The file you entered, well, wasn't found. It may not exist or it may not be where you expect. Check to make sure you are entering the correct filename and that the file actually exists.
The input string is not what you expect. Perhaps you read a blank line from previous input, etc.
Addressing reason 2: If there is already a newline on the input buffer for whatever reason, you will read a blank line with Scanner. You might want to print the value of input just before opening the file to make sure it's what you expect.
If you're seeing blank lines, just skip them. So, instead of this:
String input = in.nextLine();
scanner = new Scanner(new File(input));
Something like this instead would be immune to blank lines:
String input;
do {
input = in.nextLine().trim(); // remove stray leading/trailing whitespace
} while (input.isEmpty()); // keep asking for input if a blank line is read
scanner = new Scanner(new File(input));
And, finally, I think you can work out the reason that you're seeing 0's in your output. When you attempt to open the file with new Scanner(new File(input)); and it fails because it can't find the file, it throws an exception and the program immediately jumps to the code in your catch block. That means lines, words, and chars still have their initial value of zero (all code that modifies them was skipped).
Hope that helps.
Your println()s are in a catch block
} catch (FileNotFoundException e) {
System.out.printf("All lines: %d\nAll words: %d\nAll chars: %d\n",
lines, words, chars);
System.out.println("The end");
done = true;
}
That means you caught a FileNotFoundException. I think you can figure out from here.