I am working on homework but currently stuck.
I need to process a file and return number of characters, words, and lines.
I am particularly lost on how I can process the file. Any help would be appreciated.
you need to use Scanner scan = new Scanner(new File(your_file)); and scan the file using while(scan.hasNext()). place your counter inside the loop and count the lines,words and characters.
Try:
if (file.exists()) {
Scanner console = new Scanner(file);
//rest of code
}
Related
I'm trying to scan a line of text from a .txt file, split it up into seven numbers, change two of the numbers, and then write the new numbers back into the .txt file. The code below works fine the first time, but seems to have issues with reading from the text file a second time for the new starting String. I've done very similar things multiple times and had no issues, so I'm really not sure why I'm having problems this time around. The code I currently have is:
public void addWin(int numGuesses) throws IOException {
FileWriter writer = new FileWriter(*filepath*);
Scanner scan = new Scanner(new File(*filepath*));
String temp = "0;0;0;0;0;0;0;";
if (scan.hasNextLine()) {
temp = scan.nextLine();
}
String[] statsArr = temp.split(";");
scan.close();
statsArr[0] = Integer.toString(Integer.parseInt(statsArr[0]) + 1);
statsArr[numGuesses] = Integer.toString(Integer.parseInt(statsArr[numGuesses]) + 1);
for (int i = 0; i < statsArr.length; i++) {
writer.append(statsArr[i] + ";");
}
writer.close();
}
Some extra context if needed, this is essentially for a Wordle clone sort of thing for a Discord bot I have. numGuesses is the number of guesses it took to get the word correct. The String being written in and being read is 7 numbers divided up by a semicolon, the first number is the current win streak, the second number is number of times you've won in 1 guess, and so on. The testing I've done seems to place the error somewhere before the scanner closes. A first run through will correctly write the numbers, so if the word was guessed in 3 attempts the file will contain "1;0;0;1;0;0;0;", but the next time the method is called it essentially starts from scratch. Checking the temp variable just after the if statement on a second run through just shows "0;0;0;0;0;0;0;". Sorry for the long-windedness, just trying to provide all possibly helpful details. Thank you in advance!
-
Consider the JavaDoc which states "Whether or not a file is available or may be created depends upon the underlying platform.". So what is happening here, is that when you use new FileWriter(*filepath*) the file is being locked/created blank, so when you use new Scanner(new File(*filepath*)); and scan.hasNextLine() you get a null/empty value.
The easy solution is to simply move the FileWriter further down in your code, and only open it after the scanner has been closed. Also add an else to your if statement so you know if there is an issue with reading from the scanner:
//Move the below line to be later in the code
//FileWriter writer = new FileWriter(*filepath*);
Scanner scan = new Scanner(new File(*filepath*));
String temp = "0;0;0;0;0;0;0;";
if (scan.hasNextLine()) {
temp = scan.nextLine();
}
//Add some debugging
else{
System.out.println("ERROR no data could be read");
}
String[] statsArr = temp.split(";");
scan.close();
statsArr[0] = Integer.toString(Integer.parseInt(statsArr[0]) + 1);
statsArr[numGuesses] = Integer.toString(Integer.parseInt(statsArr[numGuesses]) + 1);
//Create the flie writer here instead
FileWriter writer = new FileWriter(*filepath*);
for (int i = 0; i < statsArr.length; i++) {
writer.append(statsArr[i] + ";");
}
writer.close();
Now assuming the file exists and can be edited, and where numGuesses = 3, then for the following contents:
1;2;3;4;5;6;7;
The output of running the code is as expected (+1 to the 0 and 3rd index)
2;2;3;5;5;6;7;
The reason you only saw 0;0;0;0;0;0;0; was because the code was failing to read from the scanner, and always using the temp value from this line String temp = "0;0;0;0;0;0;0;";. By adding the else check above we can see when it fails.
FileWriter writer = new FileWriter(*filepath*); clears the contents of the file you are trying to read from. You need to move this line after scan.close();
I am trying to read a log file word by word using a scanner and using the code
Scanner scanner = new Scanner(file);
while(scanner.hasNext()){
String word = scanner.next();
}
But the problem is that this stops after it reaches the end of the file but I need to read it as it gets generated
I tried this to solve this using the below code
Scanner scanner = new Scanner(file);
while(true){
while(!scanner.hasNext()){
Thread.sleep(1000);
}
String word = scanner.next();
}
But the code does not seem to work and gets stuck in the while loop even when the log file has more data appended to it.
Can someone point out what i am doing wrong.
I made an small snippet for reading a log file for another system. I used BufferedReader instead of Scanner. Because it will run until the end of file and still reading. Instead of using the Scanner Next.
readLine() Doc:
* #return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
And My Snippet
BufferedReader br = new BufferedReader(new InputStreamReader(file));
while (true)
{
strLine = br.readLine();
if(strLine!=null)
{
System.out.println(strLine);
}else{
Thread.sleep(100);
}
}
For some reason when I try scan a .txt file, it is failing to find any lines and thus causing the error:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
Code:
File file = new File("C:\\Users\\kayc0\\Desktop\\CkayBotBets\\mods.txt");
Scanner scanner = new Scanner(new FileInputStream (file), "UTF-8");
while(scanner.hasNextLine()){
modsList.add(scanner.nextLine());
System.out.println(scanner.nextLine());
}
I do not close the scanner.
modsList is a List that I try add each line to so I can check if a mod exists in chat (user) matches one in the list, however the error is on System.out...
I checked the .txt file exists with the following:
File f = new File("C:\\Users\\kayc0\\Desktop\\CkayBotBets\\mods.txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exists");
}
Anyone any idea why the lines are not being read?
.txt contents:
abkayckay
kayc01
Thanks, any help appreciated.
You are currently reading two lines instead of one, save the line you read to add to your list and display with the same line.
while(scanner.hasNextLine()){
String line = scanner.nextLine();
modsList.add(line);
System.out.println(line);
}
You call nextLine tice. Change to:
while(scanner.hasNextLine()){
String value = scanner.nextLine()
modsList.add(value);
System.out.println(value);
}
I'm reading words in a Scanner, but i need to know if the Scanner changes to the following line. this is for a Progress Bar(counting Lines).
Can you help me? Here is my code:
Pattern pattern = Pattern.compile("[^\\p{Alpha}]+");
try (Scanner sc = new Scanner(file)) {
while (sc.hasNext()) {
sc.useDelimiter(pattern);
long totalLines = countLines(f);//Method that count Lines
System.out.println("Reading " + totalLines + "Lines...");
word = sc.next();//here i need to know if the scanner jumps to next Line or not.
Use hasNextLine() and nextLine() methods available in Scanner class.
iterate over lines.For each line,split that using space and count number of words in that.
I am playing around with the Scanner class for learning purposes and i use it to read a very large file (60.000 lines aprox) without using the Reader class , and it stops reading after approximately 400 lines. Do i have to use a Bufferedreader inside the Scanner's constructor or the problem is something else? I want to know why this is happening. Thanks.
My code is the usual code to output all the lines.
File file1 = new File("file1");
Scanner in= new Scanner(file1);
while (scan.hasNextLine() ) {
String str = scan.nextLine();
System.out.println(str);
}
This issue is usually more common on 64 bit machines or with files having size more than 1-2 GB and does not have anything to do with heap space. Switch to BufferedReader it should work fine,
BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while((line=br.readLine())!=null)
{
// do something
}
I just experienced this very problem. It seems that it works just by changing the scanner construction. Replace this:
File file1 = new File("file1");
Scanner in= new Scanner(file1);
with this:
FileReader file1 = new FileReader("file1");
Scanner in= new Scanner(file1);
Maybe the problem appears when you build your scanner from a file without the system knowing that it is a text file.