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();
}
}
Related
I'm just trying to read text from an existing file.txt But this program shows 2 errors
for the FileReader(file)) it says : Expected 0 arguments but found 1
and for reader.readLine() it says : Cannot resolve method 'readLine' in 'BufferedReader'
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReader {
public static void main(String[] args) {
File file = new File("fileExample.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
} catch (IOException e) {
e.printStackTrace();
}
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
Rename your class to something other than BufferedReader, and import the right class from the JDK:
import java.io.BufferedReader;
Otherwise the compiler will look for a constructor of your own class.
Note about exception handling: given the code you have, if an IOException occurs when creating the BufferedReader, then the subsequent code will throw a NullPointerException. It may be better to just wrap the entire code in a try-with-resources block, or have the main method throws IOException.
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();
How can I call "getContent" inside "onCreate"?
I am getting errors like
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity: android.os.NetworkOnMainThreadException
Caused by: android.os.NetworkOnMainThreadException
main.java
protected void onCreate(Bundle savedInstanceState) {
Log.d("URL", HttpUtils.getContents("http://google.com"));
}
HttpUtils.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtils {
public static String getContents(String url) {
String contents ="";
try {
URLConnection conn = new URL(url).openConnection();
InputStream in = conn.getInputStream();
contents = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.v("MALFORMED URL EXCEPTION");
} catch (IOException e) {
Log.e(e.getMessage(), e);
}
return contents;
}
private static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
In android you cann't perform any networking task on UI thread. so you will have perform Networking task on a Different thread. For this you can use normal java Threads but this is not a good approach in android. you should use Async Task.
You can follow any good tutorial on google.
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();
Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference this Exception is thrown by JRE please help!!
here is the class
package com.example.MovieMania.fragmentTv;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.MovieMania.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
public class BackgroundTaskTv extends AsyncTask<String, Void, String[]> {
final String DEF_BASE_URL = "http:api.themoviedb.org/3/tv/popular?[api_key]";
private final Context context;
public BackgroundTaskTv(Context context) {
this.context = context;
}
public static String JsonStr; // so that JSONstring can be used by other activities
private String[] jsonParse(String movieJsonStr) throws JSONException {
final String POSTER_PATH = "poster_path"; // JSON STRING PARSING AND
// RETURN
// POSTER PATHS
JSONObject jsonObj = new JSONObject(movieJsonStr);
JSONArray resultArray = jsonObj.getJSONArray("results");
int len =resultArray.length();
String[] posters = new String[len];
for (int i = 0; i < len; i++) {
posters[i] = resultArray.getJSONObject(i).getString(POSTER_PATH);
}
for (String res : posters)
Log.v(POSTER_PATH, res);
return posters;
}
#Override
protected String[] doInBackground(String... params) {
String movieJsonStr = null;
InputStream inputStream = null;
String FINAL_URL=DEF_BASE_URL;
ImageAdapterTv.poster_paths.clear();
BufferedReader reader = null;
HttpURLConnection urlConnection = null; // READ THE INPUTSTREAM AND
// GET THE JSONSTRING
try {
URL url = new URL(FINAL_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it
// won't affect parsing)
// But it does make debugging a *lot* easier if you print
// out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
JsonStr=movieJsonStr;
Log.v("Tv string: ", movieJsonStr);
} catch (Throwable e) {
Log.e("backgroundtask", "EXCEPTION", e);
} finally {
urlConnection.disconnect();
try {
reader.close();
inputStream.close();
} catch (IOException e) {
Log.e("READER.CLOSE()", e.toString());
}
}
try {
return jsonParse(movieJsonStr);
} catch (JSONException e) {
Log.e("BACKGROUNDTASK", "EXCEPTION FROM jsonParse()", e);
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if (ImageAdapterTv.poster_paths.isEmpty()) {
for (String s : result) {
ImageAdapterTv.poster_paths.add(s);
}
}
final Activity activity = (Activity) context;
activity.runOnUiThread(new Runnable() {
#Override
// this code is written so that the grid view is populated after
// backgroundTask
public void run() { // produce results so that there is no blank
// screen on launch
GridView grid = (GridView) activity.findViewById(R.id.gridview_tv);
grid.setAdapter(new ImageAdapterTv(context));
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String path=ImageAdapterTv.poster_paths.get(position);
Intent intent=new Intent(context,DetailActivityTv.class);
intent.putExtra("poster", path);
intent.putExtra("POSITION", position);
activity.startActivity(intent);
}
});
}
});
}
}
It is a background thread which is getting the json response from an api
I dont know why this exception is thrown.
if exception happened before initializing the reader it will lead to this error because reader.close() is placed in finally block. It's good practice to always check for null before closing resources in finally
if(reader != null)
reader.close();
if(inputStream != null)
inputStream.close();
You need to check "Null" in the finally . Something is happening, and reader not created.
try {
if (reader != null) reader.close();
if (inputStream!= null) inputStream.close();
} catch (IOException e) {
Log.e("READER.CLOSE()", e.toString());
}
You do return null, but the finally is done. And in it BufferedReader reader = null;. See example:
public static void main(String[] args){
System.out.println(0);
Object o = get();
System.out.println(2);
}
public static Object get(){
try {
System.out.println(1);
return null;
} catch (Exception e){
} finally {
System.out.println("finally");
}
return null;
}
Output:
0
1
finally
2
It maybe caused because of exception in your urlconnection or your inputstream is null.
if (inputStream == null)
return null;
Your code will run finally block if exception is thrown or return is called from inputstream null checking.
Reader object to be created using inputstream is never created. So when you try close() method it's throwing null pointer exception.
You should always use null checking before using close() method on streams and readers, writers.
As it is seen from the discription the exception occurs when you are trying to close the BufferedReader reader object in the finally block as it is null at that moment. It happens because you get some other exception in your try block wich occurs before you initialize the reader or because your return statement is called, i.e somewhere in this piece of code:
URL url = new URL(FINAL_URL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
To avoid such situation, you should check your reader and inputStream for null before closing like this:
if(reader != null) {
reader.close;
reader = null;
}
if(inputStream != null) {
inputStream.close;
inputStream = null;
}
Besides take a look at this post about catching Throwables:
Is it a bad practice to catch Throwable?
Anyway, I think you shall find out why does this flow takes place as it is not what you want as far as I can understand
Why have you moved this block of code outside the first try-catch?:
try {
return jsonParse(movieJsonStr);
} catch (JSONException e) {
Log.e("BACKGROUNDTASK", "EXCEPTION FROM jsonParse()", e);
}
You can catch multiple types of exceptions from one try{}, you just have to specify them one by one.
As written above, when something goes wrong(and it does) you are finishing previous try-catch block before creating reader and everything after that. Therefore in this place your movieJsonStr is also null, and you are passing it forward to create a JSONOblect from it. This is where your next exception comes from. Move the return jsonParse(movieJsonStr); string to the place where you are certain it is the string you want to process.
sometimes this is the problem because of you are closing the BufferedReader which is not assigned any value or its value is null. so it throwing exception java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.BufferedReader.close()' on a null object reference
to overcome this problem : goto your manifest file and give INTERNET permission