Android: Text File to InputStream to String w/ new lines included - java

I've been working on a personal app and Stack Overflow has helped a bit so far, but I've now run into another issue. I'm attempting to read a basic text file stored in my source code and output it to an alert dialog. My code does this, but the dialog does not display any of my new lines.
displayChangelogDialog method
private void displayChangelogDialog() {
Context context = this;
AssetManager am = context.getAssets();
InputStream is;
// ensure that changelog is available
try {
is = am.open("changelog");
// changelog dialog
new AlertDialog.Builder(this)
.setTitle("Changelog")
.setMessage(getStringFromInputStream(is)) // convert changelog to string
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
getStringFromInputStream method
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
changelog text file
v0.0.3
- Update PPS rate for recent difficulty increase
v0.0.2
- Calculate DGM based on PPS rate
I have attempted to add "\n" to the end of each line, but it does not work and the characters "\n" are simply displayed. Thanks in advance everyone.

There is an easy and hack way to read all of the inputstream into a string object which contains all you need without read line by line.
Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
String string = scanner.hasNext() ? scanner.next() : null;
scanner.close();

readLine() will read up to a linefeed, but not include the linefeed. Also, there is no reason to use a string builder here. Change to this:
String result = "";
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;

Related

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...

I am making the bible app and I want to print a particular chapter and highlight a particular line

I am trying to do same in Eclipse to print a text file and highlight a particular line, but am only able to read text file and not the line in it. Following is my code:
import java.io.*;
public class Bible {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("temp.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Correct code to read a file line by line is
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Now comes the code to highlight.
There are multiple options to do it.
Use html codes in file e.g.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Use spannable texts
String text = "Test";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);
Use some third party library
EmphasisTextView and
Android TextView Link Builder

How to change address in url (http://localhost:8080/HELLO_WORLD) in NanoHttpd

My query is how to change how to change address in URL (http://localhost:8080/HELLO_WORLD). I change HELLO_WORLD to desire word.
#Override
public Response serve(IHTTPSession session) {
String answer = "";
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(appContext.getAssets().open("block.html")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
answer += mLine;
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
Log.d("BABAR", "EXception occured in serve()");
}
}
}
return newFixedLengthResponse(answer);
}
please suggest me how to change
I don´t know if this is what you want, but you can try.
You have to follow the steps:
1- Create a local to store your server files;
2-Then change the response in the class that is implementing the NanoHttp server to something like this:
#Override
public Response serve(IHTTPSession session) {
String answer = "";
try{
FileReader filereader = new FileReader(contextoMain.local(localyourstorethefiles)+"/yourfolder/yourfile.html");
BufferedReader reader = new BufferedReader(filereader);
String line = "";
while ((line = reader.readLine()) != null) {
answer += line;
}
reader.close();
}catch(IOException ioe) {
Log.w("Httpd", ioe.toString());
}
return newFixedLengthResponse(answer);
}
3 - Then, call the localhost:8080 without putting the 8080/yourfolder/yourfile

How to read data written to a file from one android application using another android application

I used following method to write data to a file in one android application
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE)));
writer.write("Hello world!");
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Then I tried to read that file from another android application using this method
private void readFileFromInternalStorage(){
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try
{
input = new BufferedReader(new InputStreamReader(openFileInput("myFile1.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null)
{
buffer.append(line + eol);
}
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(buffer.toString().trim());
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
Second method can't read the file. I added read write permissions also, but it shows only blank screen. What can be the error and how can I correct that ??. I'm new to Android programming and need your help.
Thanks!
The problem is
openFileOutput("myFile.txt", MODE_WORLD_WRITEABLE|MODE_WORLD_READABLE))
The documentation says:
This file is written to a path relative to your app within the
So the case is you are writing file in path relative to application 1 and trying to read it from
path relative to application 2.
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
Look below snippet to write file to SD card.
private void writeToSDCard() {
try
{
File file = new File(Environment.getExternalStorageDirectory(),
"filename");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write("Hello World");
writer.close();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Look below snippet to read file saved on SD card.
private void readFileFromSDCard() {
File directory = Environment.getExternalStorageDirectory();
// Assumes that a file article.rss is available on the SD card
File file = new File(directory + "/article.rss");
if (!file.exists()) {
throw new RuntimeException("File not found");
}
Log.e("Testing", "Starting to read");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Your best bet is to place it into the scdcard into something like /sdcard/Android/data/package/shared/

Categories