Premature EOF exception in Java using BufferedReader - java

I am trying to turn a url (its just text) into a string and I am reading the url with a BufferedReader. However, I keep getting a Premature EOF exception. Here is what I have so far.
try {
URL sUrl = new URL(url);
String result = "";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(sUrl.openStream()));
String av;
while ((av = br.readLine()) != null) {
result += av;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(result.length());
} catch (Exception e) {
e.printStackTrace();
}
Also, I tried implementing this solution, which I saw on another stackoverflow thread.
try {
URL oracle = new URL(url);
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
StringBuffer input = new StringBuffer();
int BUFFER_SIZE = 2000000;
char[] buffer = new char[BUFFER_SIZE];
int charsRead = 0;
while ((charsRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
input.append(buffer, 0, charsRead);
}
in.close();
System.out.println(input.toString().length());
} catch (Exception e) {
e.printStackTrace();
}
Both of these approached lead to the same error occuring at the .read / .readLine part of my code.
Here is the stacktrace.
java.io.IOException: Premature EOF
at java.base/sun.net.www.http.ChunkedInputStream.fastRead(ChunkedInputStream.java:257)
at java.base/sun.net.www.http.ChunkedInputStream.read(ChunkedInputStream.java:689)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:133)
at java.base/sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3501)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:185)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:161)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:326)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:392)
at com.github.doomsdayrs.jikan4java.ExampleClass.main(ExampleClass.java:99)

Related

Why can't I open this file in the assets folder? [duplicate]

I have may wifi2.txt file in my assets file directory in Android Studio. However, I keep getting a NULLPointException when I try to access it. My code is below: (Thanks so much in advance)
//CSV FILE READING
File file = null;
try {
FileInputStream is = new FileInputStream(file);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Done with CSV File Reading
In Kotlin, we can achieve this :-
val string = requireContext().assets.open("wifi2.txt").bufferedReader().use {
it.readText()
}
File file = null;
try {
FileInputStream is = new FileInputStream(file);
Actually you are not using FileInputStream anywhere. Just use this piece of code
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("wifi2.txt")));
String line;
Log.e("Reader Stuff",reader.readLine());
while ((line = reader.readLine()) != null) {
Log.e("code",line);
String[] RowData = line.split(",");
LatLng centerXY = new LatLng(Double.valueOf(RowData[1]), Double.valueOf(RowData[2]));
if (RowData.length == 4) {
mMap.addMarker(new MarkerOptions().position(centerXY).title(String.valueOf(RowData[0]) + String.valueOf(RowData[3])).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Method to read a file FROM assets:
public static String readFile(AssetManager mgr, String path) {
String contents = "";
InputStream is = null;
BufferedReader reader = null;
try {
is = mgr.open(path);
reader = new BufferedReader(new InputStreamReader(is));
contents = reader.readLine();
String line = null;
while ((line = reader.readLine()) != null) {
contents += '\n' + line;
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ignored) {
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ignored) {
}
}
}
return contents;
}
Usage: String yourData = LoadData("wifi2.txt");
Where wifi2.txt is assumed to reside in assets
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
Reference
My solution using kotlin to load text from asset file
object AssetsLoader {
fun loadTextFromAsset(context: Context, file: String): String {
return context.assets.open(file).bufferedReader().use { reader ->
reader.readText()
}
}
}
use it like this:
val text = AssetsLoader.loadTextFromAsset(context, "test.json")

Use try-with-resources or close this "BufferedReader" in a "finally" clause

Been looking for a way to fix this issue. Read all the previous answers but none helped me out.
Could it be any error with SonarQube?
public class Br {
public String loader(String FilePath){
BufferedReader br;
String str = null;
StringBuilder strb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f){
System.out.println(FilePath+" does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
}
You are not calling br.close() which means risking a resource leak. In order to reliably close the BufferedReader, you have two options:
using a finally block:
public String loader(String FilePath) {
// initialize the reader with null
BufferedReader br = null;
String str = null;
StringBuilder strb = new StringBuilder();
try {
// really initialize it inside the try block
br = new BufferedReader(new FileReader(FilePath));
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
} finally {
// this block will be executed in every case, success or caught exception
if (br != null) {
// again, a resource is involved, so try-catch another time
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return strb.toString();
}
using a try-with-resources statement:
public String loader(String FilePath) {
String str = null;
StringBuilder strb = new StringBuilder();
// the following line means the try block takes care of closing the resource
try (BufferedReader br = new BufferedReader(new FileReader(FilePath))) {
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
} catch (FileNotFoundException f) {
System.out.println(FilePath + " does not exist");
return null;
} catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
Seems like you just want to read all lines from a file. You could use this:
public String loader(String FilePath) {
try(Scanner s = new Scanner(new File(FilePath).useDelimiter("\\A")) {
return s.hasNext() ? s.next() : null;
} catch(IOException e) {
throw new UncheckedIOException(e);
}
}
The code you wrote is indeed leaking resources as you're not closing your BufferedReader. The following snippet should do the trick:
public String loader(String filePath){
String str = null;
StringBuilder strb = new StringBuilder();
// try-with-resources construct here which will automatically handle the close for you
try (FileReader fileReader = new FileReader(filePath);
BufferedReader br = new BufferedReader(fileReader);){
while ((str = br.readLine()) != null) {
strb.append(str).append("\n");
}
}
catch (FileNotFoundException f){
System.out.println(filePath+" does not exist");
return null;
}
catch (IOException e) {
e.printStackTrace();
}
return strb.toString();
}
If you're still having issues with this code, then yes, it's SonarQubes fault :-)

Reading and writing a CSV from/to a path

I would like to print line by line the file located in some directory with:
private void readWeatherDataByColumn() {
FileInputStream is = null;
try {
is = new FileInputStream(sourceDirectory);
String line = "";
BufferedReader br = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Prints throwable details
e.printStackTrace();
}
}
I get the following output:
05-21 20:13:42.018 4170-4170/com.soialab.askaruly.camera_sensor I/System.out: ������ ftypisom������isomiso2avc1mp41������
Anyone has any clues?
This must be output
05-22 17:13:22.676 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 1,22:28:23,42,92,66,224,40,0.28,0.02,0.05
05-22 17:13:22.677 5955-5955/com.soialab.askaruly.camera_sensor I/System.out: 2,22:28:24,48,92,191,224,64,0.28,0.02,0.05
Add the below code where you want to read CSV file.
String csvFileString = readFile(selectedFile.getAbsolutePath()); // path of you selected CSV File
InputStream stream = null;
try {
stream = new ByteArrayInputStream(csvFileString.getBytes(StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ReadCsv csv = new ReadCsv(stream);
List<String[]> results = new ArrayList<String[]>();
results = csv.read();
public static String readFile(String theFilePathString) {
String returnString = "";
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream((theFilePathString)), "UTF8"));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
returnString = stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return returnString;
}
ReadCsv.Class
public class ReadCsv {
InputStream in;
public ReadCsv(InputStream in) {
this.in = in;
}
public List<String[]> read() {
List<String[]> results = new ArrayList<String[]>();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
results.add(row);
}
} catch (IOException e) {
throw new RuntimeException("Error reading CSV File " + e);
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException("Error closing inputstream " + e);
}
}
return results;
}
}
Thank you for the comments and replies!
I figured out the problem. The string sourceDirectory was of the video file, not the original ".csv" text document. Therefore, some encoding problem occured, as mentioned by #TimBiegeleisen.
Now, it works totally fine with the same code. My bad, sorry...

Reading HttpURLConnection

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.
I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.
Thanks in advance!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
There are a bunch of things wrong with the code I posted in the question. Here is a working example:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It appears you are not connecting your HTTPUrlClient try con.connect()

Need help making this code more efficient

I always use this method to easily read the content of a file. Is it efficient enough? Is 1024 good for the buffer size?
public static String read(File file) {
FileInputStream stream = null;
StringBuilder str = new StringBuilder();
try {
stream = new FileInputStream(file);
} catch (FileNotFoundException e) {
}
FileChannel channel = stream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (channel.read(buffer) != -1) {
buffer.flip();
while (buffer.hasRemaining()) {
str.append((char) buffer.get());
}
buffer.rewind();
}
} catch (IOException e) {
} finally {
try {
channel.close();
stream.close();
} catch (IOException e) {
}
}
return str.toString();
}
You may find that this is fast enough.
String text = FileUtils.readFileToString(file);
AFAIK, this uses the default buffer size of 8K. However I have found larger sizes such as 64K can make a slight difference.
I would always look to FileUtils http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html to see if they had a method. In this case I would use readFileToString(File)
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29
They have already dealt with almost all the problem cases...
Try the following, it should work (well):
public static String read(File file)
{
StringBuilder str = new StringBuilder();
BufferedReader in = null;
String line = null;
try
{
in = new BufferedReader(new FileReader(file));
while ((line = in.readLine()) != null)
str.append(line);
in.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return str.toString();
}

Categories