Unable to a read a large file using BufferedReader in Java - java

I am trying to read a file using BufferedReader, but when I tried to print, It is returning some weird characters.
Code of reading file is:
private static String readJsonFile(String fileName) throws IOException{
BufferedReader br = null;
try {
StringBuilder sb = new StringBuilder();
br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while(line != null ){
sb.append(line);
System.out.println(line);
line=br.readLine();
}
return sb.toString();
} finally{
br.close();
}
}
This function is being called as :
String jsonString = null;
try {
jsonString = readJsonFile(fileName);
} catch (IOException e) {
e.printStackTrace();
}
But when I tried to print this in console using System.out.println(jsonString);, It is returning some fancy pictures.
Note: It is Working file when file size is small.
Is there any limit on size of file it can read ?

You're using the platform default encoding to read the file, which is probably encoded in UTF8. Check the actual encoding of the file, and specify the encoding:
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream("...", StandardCharsets.UTF_8));
Note that since you simply want to read everything from the file, you could simply use
String json = new String(Files.readAllBytes(...), StandardCharsets.UTF_8);

Related

problems with reading of text file in java

I use a FileWriter to save a CSV file (text file).
All seems good when I read it with a text editor like sublime text.
But when I read it with java I get some nasty characters, anyhow I try to read it.
An example of the reading:
StringBuilder sb=new StringBuilder();
try {
String ligne;
BufferedReader fichier1 = new BufferedReader(new FileReader(nom_office));
while ((ligne = fichier1.readLine()) != null) {
sb.append(ligne);
}
fichier1.close();
} catch (Exception e) {
e.printStackTrace();
}
//String totalité = new String(encoded, encoding);
String totalité = sb.toString();
the result of these following statements is:
System.out.println("##############");
System.out.println(totalité);
PK ! T��ep [Content_Types].xml �(�
�TKn�0�W�"o���EUU�,[$�L/�i"m�k�IO)�
...and so on.
why isn't it the same result as in sublime text?
BufferedReader uses default system encoding which probably isn't UTF-8 and that's what you need here. Try this:
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "UTF-8"));
Also, your IDEs console needs to be configured to use UTF-8, that's really important!

Reading a textfile in android studio

Hi I'm currently having issues with reading in a file in android studio. The file I want to read in is just a simple text file called test. This is the path of the file C:\Users\John\Documents\MadLibs\app\src\main\res\raw\test.txt. Here's what I'm trying:
BufferedReader br = new BufferedReader(new FileReader(getResources().openRawResourceFd(R.raw.test)));
I'm relitively new to android studio and really don't understand how to read in files. I assumed its just like java however everything I've tried fails. Anyone have any ideas?
Reading a textfile in android studio
FileInputStream fileInputStream=openFileInput("file.txt");
InputStreamReader InputRead= new InputStreamReader(fileInputStream);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
String rs=String.copyValueOf(inputBuffer,0,charRead);
s +=rs;
}
InputRead.close();
Log.d(TAG,s);
To read a text file as a string, you can use the following method:
// #RawRes will gives you warning if rawId is not from correct id for raw file.
private String readRawFile(#RawRes int rawId) {
String line;
try {
InputStream is = getResources().openRawResource(rawId);
// read the file as UTF-8 text.
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// Or using the following if API >= 19
//BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
inputStream.close();
line = result.toString();
} catch (IOException e) {
line = null;
}
return line;
}

Removing column names while reading content through Inputstream in Java

I have been trying to remove the column names that come when I read the content of the response returned by http get.
Initially I used http get to get a content and then I read this content using InputStream and then write to local disk as a csv file using FileOutputStream:
InputStream read_content = result.getEntity().getContent();
FileOutputStream writ = new FileOutputStream(new File(path));
byte[] buff = new byte[4096];
int length;
while ((length = read_content.read(buff)) > 0) {
writ.write(buff, 0, length);
}
Here result is the response I get from http get. This works fine but the problem is that the response also contains column names which I want to remove.
After some modification I am using this code now but the output is not coming right:
InputStream read_content = result.getEntity().getContent();
BufferedReader reader =
new BufferedReader(new InputStreamReader(read_content));
FileWriter fstream = new FileWriter(path);
BufferedWriter out = new BufferedWriter(fstream);
reader.readLine();
while (reader.readLine() != null) {
out.write(reader.read());
}
When I execute this modified code then I get garbage result. What am I doing wrong here and how can I remove the table column names?
Yout code should be something like this
BufferedReader br = null ;
BufferedWriter out = null;
try{
InputStream is = new FileInputStream(new File("C:/Space/ConnTest/Test/input.txt"));
br = new BufferedReader(new InputStreamReader(is));
out = new BufferedWriter(new FileWriter(new File("C:/Space/ConnTest/Test/output.txt")));
System.out.println("This is first line ---"+br.readLine());
String str = "";
while ((str = br.readLine()) != null) {
out.write(str);
}
System.out.println("Success");
}
catch(Exception e )
{
e.printStackTrace();
}
finally
{
if(br!=null)
{
br.close();
}
if(out!=null)
{
out.close();
}
}
Dont be confuse with whole code I just replaced your out.write(reader.read()); with
while ((str = br.readLine()) != null) {
out.write(str);
}
And I am calling br.readLine() in SYSOUT so headers will get skipped. Then I am writing the file with br.readLine()
If it's a line, and so is the rest of the content, use BufferedReader.readLine(), and skip the first line.

How can I read a text file in android with Turkish characters?

I want to read a text file and I can read with below written code. But my text file include Turkish characters like "ü", "ç", "ğ", "ö"... When I read that text file, I can see these characters. For example, my word which written in text file is "okçu" but I see on my phone like "ok?u". How can fix it?
public static String readTextFile(Context ctx, int resId) {
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputreader);
String line;
StringBuilder stringBuilder = new StringBuilder();
try {
while ((line = bufferedreader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append('\n');
}
} catch (IOException e) {
return null;
}
return stringBuilder.toString();
}
I faced this problem when I received the response from my HttpClient for the first time. I managed to solve it by specifying the encoding within the InputStreamReader object's instantiation. I hope it might help you as well.
InputStream inputStream = ctx.getResources().openRawResource(resId);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"UTF8"),8);

Java - ignoring certain characters while reading a text file

I'm trying to read a simple text file that contains the following:
LOAD
Bill's Beans
1200
20
15
30
QUIT
I need to store and print the contents line by line. I am doing so using the following code:
String inputFile = "(file path here)";
try {
Scanner input = new Scanner(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String currentLine = "";
while (!currentLine.equals("QUIT}")){
currentLine = input.nextLine();
System.out.println(currentLine);
}
input.close();
However, the output is very "messy". I am trying to avoid storing all new line characters and anything else that doesn't appear in the text file. Output is:
{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf540
{\fonttbl\f0\fmodern\fcharset0 Courier;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww9000\viewh8400\viewkind0
\deftab720
\pard\pardeftab720\ql\qnatural
\f0\fs26 \cf0 LOAD\
Bill's Beans\
1200\
20\
15\
30\
QUIT}
Any help would be greatly appreciated, thank you!
This looks like you're reading a RTF file, isn't that so, by any chance?
Otherwise, I found reading text files is most natural for me using this construct:
BufferedReader reader = new BufferedReader(
new FileReader(new File("yourfile.txt")
);
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
// do whatever with the text line
}
Because this is an RTF file, look into this for example: RTFEditorKit
If you insist on writing your own RTF reader, the correct approach would be for you to extend FilterInputStream and handle the RTF metadata in its implementation.
Just add following code into your class, then call it with path parameter. it returns all lines as List object
public List<String> readStudentsNoFromText(String path) throws IOException {
List<String> result = new ArrayList<String>();
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File(path));
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
result.add(strLine.trim());
}
//Close the input stream
in.close();
return result;
}

Categories