Nullpointer exception with Buffered readline [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
i´ve been trying to read the lines of this file to save them into an array afterwards, but when I try to print the lines to try it out it has a nullpointer on the line of :
while( (line = br.readLine()) !=null
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Main1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String line;
BufferedReader br = null ;
try {
new BufferedReader(new FileReader("/Users/Daniq/Desktop/eda/pruebaEda.txt"));
System.out.println("Done");
try {
while( (line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("error ");
}
} catch(FileNotFoundException fnfex){
System.out.println("File not found");
}
}
}

You dont initalize br reference, after try,
br = new BufferedReader...

Related

How to eliminate having an ArrayIndexOutOfBoundExceptions in Java?

I have a Java program that reads from a cvs file that looks like this:
2000;Mall1;8
2002;Mall3;23
2003;Mall4;31
...
I want the program to read from the cvs file into an array and sort the array based on the third column/field.
However, whenever I print the elements of array[2] I get an ArrayIndexOutOfBoundException. I can't see why is this happening since the array's[2] size should be already fixed.
Here is the code:
import java.util.*;
import java.io.*;
public class Prog3
{
public static void main(String[] args)
{
String csvFile = "test.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] array = line.split(cvsSplitBy);
System.out.println(array[2]);
Arrays.sort(array[2]);
System.out.println("Sorted\n" + Arrays.toString(array[2]));
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
finally {
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Any help is appreciated :)

How to read .evtx extension file through java program

I don't know if it is possible or not, but my requirement is like - I have to read data from a file called System.evtx in my java program.
While I am doing this like simple file reading I am getting some ASCII character or I can say un-readable format.
Is there any way to solve this issues.
Thanks in advance.
This is a difficult question to answer without an example of the file content, but after some googling it seems to be a windows event log file? So im unsure about the exact format but apparently they can be converted to .csv files using powershell:
Get-WinEvent -Path c:\path\to\eventlog.evtx |Export-Csv eventlog.csv
Once its in a csv format you could simple parse them in the traditional way of csv or just split by comma's etc.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "eventlog.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] line = line.split(cvsSplitBy);
for(int i=0;i<line.length;i++){
System.out.println(line[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Using java.io library in eclipse so FileInputStream can read a dat file

Goal: Print the data from a .dat file to the console using Eclipse.
(Long-Term Goal): Executable that I can pass a .dat file to and it creates a new txt file with the data formatted.
The .dat: I know the .dat file contains control points that I will need to create a graph with using ECMAScript.
Eclipse Setup:
Created Java Project
New > Class .. called the Class FileRead
Now I have FileRead.java which is:
1/ package frp;
2/
3/ import java.io.BufferedReader;
4/ import java.io.File;
5/ import java.io.FileReader;
6/
7/ public class FileRead {
8/
9/ public static void main(String[] args) {
10/ FileReader file = new FileReader(new File("dichromatic.dat"));
11/ BufferedReader br = new BufferedReader(file);
12/ String temp = br.readLine();
13/ while (temp != null) {
14/ temp = br.readLine();
15/ System.out.println(temp);
16/ }
17/ file.close();
18/ }
19/
20/ }
Please note this approach was borrowed from here: https://stackoverflow.com/a/18979213/3306651
1st Challenge: FileNotFoundException on LINE 10
Screenshot of Project Explorer:
QUESTION: How to correctly reference the .dat file?
2nd Challenge: Unhandled exception type IOException LINES 12, 14, 17
QUESTION: How to prevent these exceptions?
Thank you for your time and effort to help me, I am recreating Java applets using only JavaScript. So, I'm looking to create java tools that extract data I need to increase productivity. If you are interested in phone/web app projects involving JavaScript, feel free to contact me 8503962891
1. Without changing your code, you must place the file in the project's root folder.
Otherwise, reference it as src/frp/dichromatic.dat
2. Doing something like this:
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error when reading");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
3. Creation of a new txt file "formatted". In this example, the formatting will be settings the characters to uppercase.
public static void main(String[] args) {
FileReader file = null;
BufferedWriter bw = null;
File outputFile = new File("output.formatted");
try {
file = new FileReader(new File("dichromatic.dat"));
} catch (FileNotFoundException e1) {
System.err.println("File dichromatic.dat not found!");
e1.printStackTrace();
}
try {
bw = new BufferedWriter(new FileWriter(outputFile));
} catch (IOException e1) {
System.err.println("File is not writtable or is not a file");
e1.printStackTrace();
}
BufferedReader br = new BufferedReader(file);
String line;
String lineformatted;
try {
while ((line = br.readLine()) != null) {
lineformatted = format(line);
bw.write(lineformatted);
// if you need it
bw.newLine();
}
} catch (IOException e) {
System.err.println("Error when processing the file!");
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
System.err.println("Unexpected error");
e.printStackTrace();
}
}
}
}
public static String format(String line) {
// replace this with your needs
return line.toUpperCase();
}
I would strongly recommend spending some time reading through the Java Trails Tutorials. To answer your specific question, look at Lesson: Exceptions.
To oversimplify, just wrap the file-handling code in a try...catch block. By example:
package frp;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class FileRead {
public static void main(String[] args) {
try {
FileReader file = new FileReader(new File("dichromatic.dat"));
BufferedReader br = new BufferedReader(file);
String temp = br.readLine();
while (temp != null) {
temp = br.readLine();
System.out.println(temp);
}
file.close();
} catch (FileNotFoundException fnfe) {
System.err.println("File not found: " + fnfe.getMessage() );
} catch (IOException ioe) {
System.err.println("General IO Error encountered while processing file: " + ioe.getMessage() );
}
}
}
Note that ideally, your try...catch should wrap the smallest possible unit of code. So, wrap the FileReader separately, and "fail-fast" if the file isn't found, and wrap the readLine loop in its own try...catch. For more examples and a better explanation of how to deal with exceptions, please reference the link I provided at the top of this answer.
Edit: issue of file path
Not finding the file has to do with the location of the file relative to the root of the project. In your original post, you reference the file as "dichromatic.dat" but relative to the project root, it is in "src/frp/dichromatic.dat". As rpax recommends, either change the string that points to the file to properly reference the location of the file relative to the project root, or move the file to project root and leave the string as-is.

Java : Problems accessing and writing to file

I was testing out writing to files with this code:
package files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class FileTest1
{
public static void main(String[] args)
{
try
{
try
{
File f = new File("filetest1.txt");
FileWriter fWrite = new FileWriter(f);
BufferedWriter fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
}
catch(FileNotFoundException e)
{
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
}
}
catch(IOException e)
{
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
Nothing happens when it is executed.
"This is a test!" is not written, nor the StackTrace or the "A/An [exception] occurred!"...
I don't know what's causing the problem. I have fileTest1.txt in the package right under the file...
A BufferedWriter does just that, it buffers the output before it is written to the destination. This can make the BufferedWriter faster to use as it doesn't have to write to a slow destination, like a disk or socket, straight away.
The contents will be written when the internal buffer is to full, you flush the Writer or close the writer
Remember, if you open it, you should close it...
For example...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileWriter {
public static void main(String[] args) {
try {
BufferedWriter fileWrite = null;
try {
File f = new File("filetest1.txt");
System.out.println("Writing to " + f.getCanonicalPath());
FileWriter fWrite = new FileWriter(f);
fileWrite = new BufferedWriter(fWrite);
fileWrite.write("This is a test!");
fileWrite.flush();
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
fileWrite.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
try {
BufferedReader br = null;
try {
File f = new File("filetest1.txt");
System.out.println("Reading from " + f.getCanonicalPath());
FileReader fReader = new FileReader(f);
br = new BufferedReader(fReader);
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
}
} catch (FileNotFoundException e) {
System.out.print("A FileNotFoundException occurred!");
e.printStackTrace();
} finally {
try {
// Note, BufferedWriter#close will also close
// the parent Writer...
br.close();
} catch (Exception exp) {
}
}
} catch (IOException e) {
System.out.println("An IOException occurred!:");
e.printStackTrace();
}
}
}
If you are using Java 7, you may like to take a look at try-with-resources
After
fileWrite.write("This is a test!");
you have to flush() the writer. To avoid leaking of resources you should also close() the writer (which automatically flushes it).
So you need to add:
fileWrite.close();
Use BufferedWriter.flush() and BufferedWriter.close(). Additional info here http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
You must call close() or at least flush() on the writer in order for the buffer to be really written to the file.

Error in Writing a text file "Exception in thread "main" " [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'
I am trying to write a byte array in a text file. It is giving me error:
java.lang.NoSuchMethodError: main
Exception in thread "main"
The code i am using is as under
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class writefile {
//it works well
public static void main()throws IOException{
Writer output = null;
byte[] a= {1,2,3,4,5,6};
try {
String text = "abcd...\n";
String str3 = text.concat("the end");
String NL = System.getProperty("line.separator");
str3 = str3.concat(NL);
str3= str3.concat("next line");
for ( int i=0; i < a.length; i++){
str3 = str3.concat(NL);
str3= str3.concat(" " +a[i]);
}
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(str3);
System.out.println("Your file has been written");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Kindly help how can i resolve the problem.
The main method of a Java program must take an argument of type String[] representing the arguments (if any) passed to the program on launch.
the main signature must contain String[] argument

Categories