How can I count the number of lines in a file?
Below is the code I have written, but with an exception.
import java.io.File;
import java.net.URI;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args)throws Exception {
String[] MovieList = new String[25];
File MovieFile= new File("TheMovieList.txt");
Scanner ms = new Scanner(MovieFile);
while(true){
int i= ms.nextInt();
System.out.println();
}
}
}
And I had
Exception in thread "main" java.util.InputMismatchException
What's wrong, and how can I fix this?
You can check, that the input can be interpreted as an int value:
...
if (ms.hasNextInt()) {
int i= ms.nextInt();
...
}
To count the lines in the file you can do this.
import java.io.File;
import java.net.URI;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args)throws Exception {
File MovieFile= new File("TheMovieList.txt");
Scanner ms = new Scanner(MovieFile);
int count = 0;
while (ms.hasNextLine()) {
count++;
ms.nextLine();
}
System.out.println("Number of lines in the file is " + count);
}
}
Related
I've finally gotten around to learning Java and I'm trying to write an interpreter for an esolang. I looked up a few tutorials and wrote this code.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class NDBall {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get(input);
List<String> code = new ArrayList<String>();
code = Files.readAllLines(path);
}
}
However, the readAllLines function keeps giving me an error, and I don't know why. It won't tell me what the error is, and everything else seems fine. I'm doing it exactly as the tutorials I looked up told me.
Is there some mistake I made?
The below code will work for you. have hard coded the path so escape characters are taken care of:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Solution {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get("C:\\Users\\xyz\\Desktop\\imp.txt");
List<String> code = new ArrayList<String>();
try {
code = Files.readAllLines(path, StandardCharsets.UTF_8);
code.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
im trying to read a csv with dummy data into java arraylists. I don't know what happened, but I get the described error message above the next day I started the program again.
Here's my Code. I hope you don't get irritated by the german variables. I think the structure is important.
package Aufgabe2;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import Aufgabe2.Models.Einlagekonto;
import Aufgabe2.Models.Girokonto;
import Aufgabe2.Models.Kunde;
public class Kundenreport {
public static void main(String[] args) throws ParseException, FileNotFoundException {
Scanner scanner = new Scanner(System.in);
List<Kunde> kunde = new ArrayList<Kunde>();
String pathKunden = "/Users/testuser/OneDrive/03_Privat/05_Code/01_Java/university/project8/src/Aufgabe2/Data/Kunden.csv";
String line = null;
try {
BufferedReader kundenReader = new BufferedReader(new FileReader(pathKunden));
kundenReader.readLine();
while ((line = kundenReader.readLine()) != null) {
String[] valuesKunden = line.split(";");
kunde.add(new Kunde(valuesKunden[0], valuesKunden[1], valuesKunden[2], valuesKunden[3]));
}
kundenReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the "Kunde" (engl. Customer) Class which inherits from the abstract class "Konto"
package Aufgabe2.Models;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import Aufgabe2.Abstract.Konto;
public class Kunde extends Konto {
public Kunde() {
}
// Kunde ohne Konten
public Kunde(String kundenNr, String name, String vorname, String kundeSeit) {
super(kundenNr, name, vorname, kundeSeit);
}
And the "Konto" (engl. account) class possesses the attributes, abstract methods and getters/setter methods.
package Aufgabe2.Abstract;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
import Aufgabe2.Models.Kunde;
public abstract class Konto {
public final static Date today = new Date();
public Scanner scanner = new Scanner(System.in);
public static SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.GERMAN);
private String kundenNr, name, vorname, kundeSeit;
private double kontoStdGiro, kontoStdEinlage;
private String anlagedatum, faelligkeitsdatum;
public Konto() {
}
// Nur Kunde ohne Konten
public Konto(String kundenNr, String name, String vorname, String kundeSeit) {
this.kundenNr = kundenNr;
this.name = name;
this.vorname = vorname;
this.kundeSeit = kundeSeit;
}
I was searching for a while and thankful for every advise from you.
Thanks!
By the way, here is the folder structure of the project:
Screenshot of repository
Most languages - such as Java or Python are zero-indexed, meaning they start from 0 instead of 1 like we normally do when counting. So when accessing a particular index we have to go one less than its number, for example, if we want the second element in array arr, we would do arr[1]. So in this case an array of length one only has one index, meaning arr[0]. For further reading on zero index here's a link: https://softwareengineering.stackexchange.com/questions/110804/why-are-zero-based-arrays-the-norm
Here i have written a program. I want to get input by a scanner from system. Then I want to show output from file. But after giving input , a message " The file is modyfied by another program " is shown. But i cannot see anything in this file. Please give me a suggestion to solve the problem.
package eighthLecture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Filetester {
public static void main(String[] args) {
File outFile = new File("C:/Users/nafiulislam/Desktop/naficlass.txt");
try {
FileWriter fileWriter=new FileWriter(outFile);
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String tempString = scanner.nextLine();
System.out.println(tempString);
fileWriter.write(tempString);
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have text log files which follow this format:
18:27:08.231 [main] DEBUG sample_client - This is a DEBUG message,
line 39 Location 7 18:27:09.231 [main] DEBUG sample_client - This is
anr DEBUG message, line 39 Location 17 18:27:10.231 [main] DEBUG
sample_client - This is a DEBUG message, line 56 Location 23
I would like to obtain the most recent integer, that comes after the String "Location" - here it is 23.
The following is my Scanner class so far :
import org.apache.logging.log4j.flume; */
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest { /* BEGINBRAC */
public static void main(String[] args) throws IOException {
int mostRecentLocation = 0;
Scanner scanner = new Scanner ("LogbackTutorialError.txt");
while (scanner.hasNextLine() ) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains("Location")){
System.out.print("the location is " + mostRecentLocation );
}
}
}
}// end class ScannerTest
How do I go about getting the most recent number after Location ?
You could do something with String.substring(int) to remove everything from Location on. Something like,
if (lineFromFile.startsWith("Location")) {
int mostRecentLocation = Integer.parseInt(lineFromFile
.substring(1 + "Location".length()).trim());
System.out.println("the location is " + mostRecentLocation);
}
The following code shows how to create it.
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest {
public static void main(String[] args) throws FileNotFoundException {
int mostRecentLocation = 0;
File newFile = new File("LogbackTutorialError.log");
Scanner scanner = new Scanner (newFile);
int result = 0;
while (scanner.hasNextLine() ) {
String lineFromFile = scanner.nextLine();
Scanner lineScanner = new Scanner(lineFromFile);
if(lineScanner.findInLine("Location") != null){
result = lineScanner.nextInt() ;
mostRecentLocation = result;
}
}
System.out.println(" The location is : " + result );
}
}// end class ScannerTest
So I have a few other classes like this one, I call the method in using an object in the run file. I want to write every output of every class into the same text file. However at the moment only one output is being saved to the text file, as it is overwriting each time, how do I do this using a print writer seen below?
Any guidance is much appreciated!
Class:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class LineCounter {
public static void TotalLines() throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
PrintWriter out = new PrintWriter(new FileWriter("C:\\Users\\Sam\\Desktop\\Report.txt"));
int linetotal = 0;
while (sc.hasNextLine()) {
sc.nextLine();
linetotal++;
}
out.println("The total number of lines in the file = " + linetotal);
out.close();
System.out.println("The total number of lines in the file = " + linetotal);
}
}
Run File:
package cw;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
import java.io.IOException;
public class TextAnalyser {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(TextAnalyser.class.getResourceAsStream("test.txt"));
LineCounter Lineobject = new LineCounter();
WordCounter Wordobject = new WordCounter();
NumberCounter Numberobject = new NumberCounter();
DigitCounter Digitobject = new DigitCounter();
SpaceCounter Spaceobject = new SpaceCounter();
NumberAverage Noavgobject = new NumberAverage();
WordAverage Wordavgobject = new WordAverage();
Palindromes Palindromeobject = new Palindromes();
VowelCounter Vowelobject = new VowelCounter();
ConsonantCounter Consonantobject = new ConsonantCounter();
WordOccurenceTotal RepeatsObject = new WordOccurenceTotal();
Lineobject.TotalLines();
Wordobject.TotalWords();
Numberobject.TotalNumbers();
Digitobject.TotalDigits();
Spaceobject.TotalSpaces();
Noavgobject.NumberAverage();
Wordavgobject.WordAverage();
Vowelobject.TotalVowels();
Consonantobject.TotalConsonant();
Palindromeobject.TotalPalindromes();
//RepeatsObject.TotalRepeats();
}
}
You want to use the second argument of the FileWriter constructor to set the append mode:
new FileWriter("name_of_your_file.txt", true);
instead of:
new FileWriter("name_of_your_file.txt");