java scanner nullpointer exception when end of file is reached - java

Okay I may be doing something stupid or this should be a simple fix but basically I have a text file I am reading from with a scanner object and I am getting a nullpointer exception when I reach the end of the file I was wondering how to get fix this
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Scanner;
public class FileAccess {
public static void main (String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("move_list.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
}
finally {
if (s != null) {
s.close();
}
}
}
}
Once it reaches the end I get:
Exception in thread "main" java.lang.NullPointerException
at java.util.regex.Matcher.toMatchResult(libgcj.so.10)
at java.util.Scanner.myCoreNext(libgcj.so.10)
at java.util.Scanner.hasNext(libgcj.so.10)
at FileAccess.main(FileAccess.java:13)

Try using
while (s.hasNextLine()) {
String line = s.nextLine();
System.out.println(line);
}
s.close();

Related

It seems my IntelliJ cannot find my csv file? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
So ive made a class to keep track of the data i've imported:
package com.company;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException{
String file = "Users/mathiaspoulsen/Desktop/SP3MarioPizza/pizzas.csv";
ArrayList <Pizza> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = br.readLine();
while ((line = br.readLine()) != null) {
line = br.readLine();
String [] lineArr = line.split(",");
Pizza pizza = new Pizza (Integer.parseInt(lineArr[0]),lineArr[1],Double.parseDouble(lineArr[2]));
content.add(pizza);
}
} catch (FileNotFoundException e) {
//Some error logging
}
return content;
}
I have then tried to run it in the main method to see if it loads the csv-file corectly. Like this:
package com.company;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws IOException {
/* int i = 0;
String fileName = "pizzas.csv";
Path pathToFile = Paths.get(fileName);
System.out.println(pathToFile.toAbsolutePath());
*/
// ArrayList<Pizza> pizzas = ImportData.readData();
System.out.println(ImportData.readData());
}
}
The output of this program is: []
Why dont it display the pizzas? The pizzas in the csv-file a structured like this:
PizzaNumber(int),PizzaName(String), price(double)
1,MARGHERITA,69.00
You read the line multiple times which most likely was causing your issue just read the line once and check to make sure it is not null in the while statement before parsing it. Also, it would be better to check to make sure the parse is successful.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class ImportData {
public ImportData() {
}
public static ArrayList<Pizza> readData() throws IOException {
String file = "/Users/your/path/pizza.csv";
ArrayList<Pizza> content = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
String[] lineArr = line.split(",");
content.add(new Pizza(Integer.parseInt(lineArr[0]), lineArr[1], Double.parseDouble(lineArr[2])));
}
}
catch (FileNotFoundException e) {
System.out.println(e);
}
return content;
}
}

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.

Reading numbers from a file and creating an array (java)

I cannot figure out how to make this txt file with numbers into an array, I am able to get it to read and print the screen but I need to be able to organize the numbers and delete the duplicates. This is what my code looks like so far
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class File {
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
System.out.format(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
}
}
}
I would recommend using an ArrayList rather than an Array.
With an array you would have to parse through the list and calculate the line count before you could even initialize it. An ArrayList is much more flexible as you don't have to declare how many values will be added to it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class File {
private List<Integer> data = new ArrayList<Integer>(); //Create ArrayList
public static void main(String[] args) {
String filename = "C:/input.txt";
File rfe = new File();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input));//Add each parsed number to the arraylist
System.out.println(input); // Display the line on the monitor
}
}
catch(FileNotFoundException fnfe) {
}
catch(IOException ioe) {
}
catch(Exception ex) { // Not required, but a good practice
ex.printstacktrace(); //Usually good for general handling
}
}
}

null pointer exception in reading tsv file

hi can anybody help me with below code. why this is throwing null pointer exception and how i can avoid it.
i am trying to read a tsv file and csv file and do some processing with this.
when i am calling getDictionaryValues function it throwing null pointer exception.
package com.ugam.qa.tittle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class TittleMatch {
private static TittleMatchUtil tMU;
public static void main(String[] args) {
String fullname="d:/files/listing/Headphones.tsv";
Set<String> attributeSet=new HashSet<String>();
attributeSet.add("Storage Type");
attributeSet.add("Recording Definition");
attributeSet.add("Type");
attributeSet.add("Brand");
BufferedReader in = null;
try
{
System.out.println("file found");
in= new BufferedReader(new FileReader(fullname));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String str;
String prv_Pid="-1";
try {
str = in.readLine();
while ((str = in.readLine()) != null) {
if (str.trim().length() == 0 ) {
System.out.println("while loop");
continue;}
String[] values = str.split("\\t");
//System.out.println(values.length);
if(prv_Pid=="-1" || values[9]==prv_Pid)
{
if(attributeSet.contains(values[12]))
{
ArrayList<Set<String>> dicValues=new ArrayList<Set<String>>();
if(values[12]!=null && values[13]!=null)
{
dicValues=tMU.getDictionaryValues(values[12],values[13]);
}
//Set<String> tittle=new HashSet<String>();
//tittle.add(values[8]);
//System.out.println(tittle);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Obviously this variable is evaluated to null, since you never assign a value to it.
private static TittleMatchUtil tMU;
One solution would be assigning a new TittleMatchUtil object to the variable:
private static TittleMatchUtil tMU = new TittleMatchUtil();
and another one is to make the getDictionaryValues() method static, which I wouldn't do, because it may require more code re-factoring.

Reversing Lines With Recursion Java

I am just trying to reverse the lines which I receive from the input, but every single time I run my code, the output.txt file is empty. What am I missing?
It appears mostly correct to me, even the recursion passage.
Thanks
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReverseLines {
public static BufferedReader input;
public static PrintWriter output;
public static void main(String[] args) throws Exception{
input = new BufferedReader(new FileReader(args[0]));
output = new PrintWriter(new FileWriter(args[1]));
reverse(input, output);
}
public static void reverse( BufferedReader input, PrintWriter output)
throws Exception {
String line = input.readLine();
if(line != null) {
reverse (input, output);
output.println(line);
}
}
}
Close the PrintWriter in your main method:
output.close();
do output.flush() and check whether it works!

Categories