unexpected exception: java.lang.NullPointerException [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Example {
public static void main(String[] args) {
BufferedReader input = null;
BufferedWriter output = null;
try{
int c;
input = new BufferedReader(new FileReader("readfile.txt"));
output = new BufferedWriter(new FileWriter("writefile.txt"));
while ((c=input.read())!= -1) {
output.write(c);
}
} catch (FileNotFoundException fnfe){
System.err.println("The file was not found.");
fnfe.getMessage();
} catch (IOException ioe) {
System.err.println("The file could not be read.");
ioe.getMessage();
}finally {
try {
output.close();
} catch (IOException e) {
System.err.println("The file was not opened.");
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
System.err.println("The file couldn't be closed.");
e.printStackTrace();
}
}
}
}
The above code throws an unexpected exception - NullPointerException in one of the try block on the following line:
output.close();.
Can anyone explain the reason for that? Any help would be appreciated. Thanks in advance.

The line
input = new BufferedReader(new FileReader("readfile.txt"));
might throw before output is initialized. Hence output == null when attempting to execute output.close();. Maybe you meant something like this instead:
if (output != null)
output.close();

Related

Reading DNA text file using JAVA

I want to read the DNA text file of bacteria using java i made this
code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
// implements a simplified version of "type" command provided in Windows given
// a text file name(s) as argument, it prints the content of the text file(s) on console
class Type {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\mohamed\\Downloads\\dataset_2_6.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
but the output is null
, it work when using small text file

Read a txt File with RandomAccessFile (Java)

I try to output the content of a text file. But I don't know how to work with the RandomAccessFile. I haven't found good examples at google. I hope for some help.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadTextFile {
public static void main(String[] args) throws IOException {
File src = new File ("C:/Users/hansbaum/Documents/Ascii.txt");
cat(src);
}
public static void cat(File quelle){
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
// while(datei.length() != -1){
// datei.seek(0); //
// }
} catch (FileNotFoundException fnfe) {
System.out.println("Datei nicht gefunden!");
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}
related from doc
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r")){
String line;
while ( (line = datei.readLine()) != null ) {
System.out.println(line);
}
System.out.println();
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
System.err.println(ioe);
}
What makes you think you need a RandomAccessFile? The easiest way is probably to use nio's convenience methods. With those, reading a file is as close to a one-liner as it gets in Java.
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.io.IOException;
class Test {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("./Test.java"), StandardCharsets.UTF_8);
for (String l: lines)
System.out.println(l);
}
}
Be aware however that this is not a good idea if you happen to work with very large files as they might not fit into memory.
Try to create Stream from FileChannel to read and write in another file out.txt like this:
try (RandomAccessFile datei = new RandomAccessFile(quelle, "r").getChannel();){
// Construct a stream that reads bytes from the given channel.
InputStream is = Channels.newInputStream(rChannel);
File outFile = new File("out.txt");
// Create a writable file channel
WritableByteChannel wChannel = new RandomAccessFile(outFile,"w").getChannel();
// Construct a stream that writes bytes to the given channel.
OutputStream os = Channels.newOutputStream(wChannel);
// close the channels
is.close();
os.close();

IOException, must be caught or declared to be thrown

This code is from the below link. I tried to run it but got the following error:
Thelink
D:\Android_Dosyalar\Proje\TextToArray\app\src\main\java\chessactivetexttoarray\com\texttoarray\MainActivity.java
Error:(40, 21) error: unreported exception IOException; must be caught or declared to be thrown
Error:(41, 22) error: unreported exception IOException; must be caught or declared to be thrown
Error:(42, 21) error: unreported exception IOException; must be caught or declared to be thrown
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.
What possibly is wrong. The following part is underlined in red as well.
New to android. Novice level.
Thank you all in advance.
Regards
br.close();
isr.close();
is.close();
Read and split text file into an array - Android
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager manager;
String line = null;
List<String[]> xyzList = new ArrayList<String[]>();
String[][] xyz;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
manager = getAssets();
is = manager.open("C:\\Users\\serhat\\Copy\\satranc\\Akdag_Reportaj\\dan_akdag.pgn");
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
xyzList.add(line.split(" "));
}
xyz = (String[][]) xyzList.toArray();
} catch (IOException e1) {
Toast.makeText(getBaseContext(), "Problem!", Toast.LENGTH_SHORT).show();
} finally {
br.close();
isr.close();
is.close();
}
}
}
The close methods can throw an exception. So they need to catch them.
} finally {
try {
br.close();
isr.close();
is.close();
} catch(IOException e) {
e.printStackTrace();
}
}
You also have one other issue in your code that will cause it to fail at run time. You are trying to use the AssetManager to open a file on your windows computer and not the phone. Move the file into your your projects' assets folder and then change
is = manager.open("C:\\Users\\serhat\\Copy\\satranc\\Akdag_Reportaj\\dan_akdag.pgn");
to
is = manager.open("dan_akdag.pgn");
You need to catch the IOException that the close methods may throw:
e.g.
finally {
try {
br.close();
isr.close();
is.close();
} catch (IOException e) {
// dosomething
}
}
The close method throws an IOException. You don't have a try/catch block surrounding the close methods. Your code should look like:
...
} finally {
try {
br.close();
isr.close();
is.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}

Reading/storing a text file in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to read a text file in the following format and store it (java).
The format of the text file is like this:
1111
1010
1100
1000
It's a Hadamard matrix as you can tell. I'm very new to java and can't figure out how to accomplish this. I want to be able to perform computations on the matrix.
Can someone help me with this
This is not tough. you should learn File Handling in java. there is plenty of tutorials over internet. Use Google. I am posting here the code as required. if this helpful vote me up as i needed and accept it as answer. (courtesy: http://www.mkyong.com/)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderWriter {
public static void main(String[] args) {
Reader();
Writer();
}
static void Reader(){
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\matrix.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
static void Writer(){
try {
String content = "1010\n1111\n0000\n0101\n";
System.out.println("Writing ... \n"+content);
File file = new File("D:\\matrix.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Something is wrong with this code

My homework assignment says "Write a program that reads a file and writes a copy of the file to another file with line numbers inserted" I have this code but something's wrong, can anyone help please? Thank you in advance
ShowFile:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class ShowFile {
public static void main(final String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch (final FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch (final ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = fin.read();
if (i != -1)
System.out.print((char) i);
} while (i != -1);
fin.close();
}
}
CopyFile:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
class CopyFile {
public static void main(final String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch (final FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch (final FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch (final ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.read();
if (i != -1)
fout.write(i);
} while (i != -1);
} catch (final IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
This is the error message-
Exception in thread "main" java.lang.NoClassDefFoundError: C
Caused by: java.lang.ClassNotFoundException: C
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
How about this ...
BufferedReader reader = new BufferedReader(new FileReader("infile"));
BufferedWriter writer = new BufferedWriter(new FileWriter("outfile"));
String line;
int lineNumber = 0;
while((line = reader.readLine()) != null) {
writer.write(++lineNumber + " " + line);
writer.newLine();
}
writer.close();
reader.close();
I think that the problem must be in the way that you are running the program. The exception seems to be saying that it can't find a class called "C".
My guess is that you have supplied the name of the class to be executed as a pathname not as a classname. Please read the manual page for the java command carefully.
There is no problem in your code.
I think you just have passing wrong argument.
Let say you have this readme.txt in your drive,
you must run this, like this :
java ShowFile "C:\readme.txt"

Categories

Resources