I would like to know how can I read a text file from assets character by character.
For example, if I have this file "text.txt" and inside of it "12345", I would like to read all numbers one by one.
I've already looked for this but I can't find any solution.
Thanks.
Use getAssets().open("name.txt") to retrieve an InputStream on assets/name.txt, then read it in as you wish.
Thanks CommonsWare for your answer :) Along with my link where I did replied to Eric, I did add your piece of code and here is the result (fully working):
AssetManager manager = getContext().getAssets();
InputStream input = null;
try {
input = manager.open("test.txt");
} catch (IOException e1) {
Log.d("ERROR DETECTED", "ERROR WHILE TRYING TO OPEN FILE");
}
try {
char current;
while (input.available() > 0) {
current = (char) input.read();
Log.d("caracter", ""+current);
}
} catch (IOException e) {
e.printStackTrace();
}
Thanks for your help guys :)
EDIT: The next code will read all file lines while the above not:
AssetManager manager = getContext().getAssets();
InputStream input = null;
InputStreamReader in = null;
try {
input = manager.open("teste.txt");
in = new InputStreamReader(input);
} catch (IOException e1) {
Log.d("ERROR DETECTED", "ERROR WHILE TRYING TO OPEN FILE");
}
try {
char current;
while (in.ready()) {
current = (char) in.read();
Log.d("caracter", ""+current);
}
} catch (IOException e) {
e.printStackTrace();
}
To read files in character units, often used to read text, Numbers, and other types of files
public static char[] readFileByChars(File file) {
CharArrayWriter charArrayWriter = new CharArrayWriter();
char[] tempBuf = new char[100];
int charRead;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((charRead = bufferedReader.read(tempBuf)) != -1) {
charArrayWriter.write(tempBuf, 0, charRead);
}
bufferedReader.close();
return charArrayWriter.toCharArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Related
I want to read data of type double saved in a .txt file from a previously specified folder. I've implemented the following code to read data then put them in an array of type double named savg1. when I run my application , it going to crash and the application stop. I tried to debug the application step by step and found that crash happens when the code reaches to savg1[i] = Double.parseDouble(str).
public void filereader()
{
InputStream is=this.getResources().openRawResource(R.raw.nums);
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
int i=0;
try
{
if (is !=null)
{
str=br.readLine();
while (str != null) {
savg1[i] = Double.parseDouble(str);
i++;
str=br.readLine();
}
is.close();
br.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
I am a newbie in Android developing so excuse me about my elementary question. Can anybody guide me how I can solve this problem?
Use following code to read data from your file. Note that in this method each number should be in a separate line:
double svg1[] = new double[10];
try {
InputStream is = getResources().openRawResource(R.raw.data);
DataInputStream dis = new DataInputStream(is);
while (dis.available() > 0) {
String test = dis.readLine();
double a = Double.parseDouble(test);
}
}catch (Exception e){
e.printStackTrace();
}
You can use file scanner for reading double type data saved in a text file as bellow:
public void fileReader(){
Scanner scan;
File file = new File("resources\\scannertester\\data.txt");
int idx = 0;
try {
scan = new Scanner(file);
while(scan.hasNextDouble())
savg1[idx++] = scan.nextDouble();
} catch (FileNotFoundException error) {
error.printStackTrace();
}
scan.close();
}
I'm participating in an online Android course and have (so far) gotten no response on their forum to this issue. I'm using Android Studio on Windows 8.1.
I have the following function to read a file and load an adapter:
private void loadItems() {
BufferedReader reader = null;
try {
FileInputStream fis = openFileInput(FILE_NAME);
reader = new BufferedReader(new InputStreamReader(fis));
String title = null;
String priority = null;
String status = null;
Date date = null;
while (null != (title = reader.readLine())) {
priority = reader.readLine();
status = reader.readLine();
date = ToDoItem.FORMAT.parse(reader.readLine());
mAdapter.add(new ToDoItem(title, Priority.valueOf(priority),
Status.valueOf(status), date));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My questions are:
I don't find the file named by the constant FILE_NAME anywhere on my hard drive. If the file doesn't exist shouldn't openFileInput() throw FileNotFoundException?
Why does InputStreamReader not throw an error?
Via the debugger, I've watched as The logic guarding entry into the WHILE construct happily allows a null value in the title variable to enter the loop. Am I missing something here?
Thanks in advance for any light anyone can shed!!
Markb
I am facing one problem in StringBuffer concatination for appending large characters of String from JSONArray.
My data is huge and it is coming in log after iteration of 205 indexes of Array properly
but when I am appending each row String in StringBuffer or StringBuilder from JSONArray, so it is taking on 4063 characters only not appending all characters present in JSON Array but iteration doesn't break and goes till complete 204 rows.
String outputFinal = null;
try {
StringBuilder cryptedString = new StringBuilder(1000000);
JSONObject object = new JSONObject(response);
JSONArray serverCustArr = object.getJSONArray("ServerData");
Log.d("TAG", "SurverCust Arr "+serverCustArr.length());
for (int i = 0; i < serverCustArr.length(); i++) {
String loclCryptStr = serverCustArr.getString(i);
Log.d("TAG", "Loop Count : "+i);
cryptedString.append(loclCryptStr);
}
Log.d("TAG", "Output :"+cryptedString.toString());
CryptLib _crypt = new CryptLib();
String key = this.preference.getEncryptionKey();
String iv = this.preference.getEncryptionIV();
outputFinal = _crypt.decrypt(cryptedString.toString(), key,iv); //decrypt
System.out.println("decrypted text=" + outputFinal);
} catch (Exception e) {
e.printStackTrace();
}
My JSONArray contacts 119797 characters in 205 and after iteration for appending in StringBuffer, I have to decrypt it with library that takes string for decryption. But StringBuffer is not having complete data of 119797 characters.
And Exception is because string is not complete, I am enclosing files on link below for reference and also using cross platform CryptLib uses AES 256 for encryption easily find on Github
3 Files With Original and Logged text
Dont use StringBuffer , instead use StringBuilder ..here's the detailed Explaination
http://stackoverflow.com/questions/11908665/max-size-for-string-buffer
Hope this helps. :)
EDIT
this is the code that i used to read whole string ...
public void parseLongString(String sourceFile, String path) {
String sourceString = "";
try {
BufferedReader br = new BufferedReader(new FileReader(sourceFile));
// use this for getting Keys Listing as Input
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
br.close();
sourceString = sb.toString();
sourceString = sourceString.toUpperCase();
System.out.println(sourceString.length());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = new File(path);
FileWriter fileWriter = null;
BufferedWriter bufferFileWriter = null;
try {
fileWriter = new FileWriter(file, true);
bufferFileWriter = new BufferedWriter(fileWriter);
} catch (IOException e1) {
System.out.println(" IOException");
e1.printStackTrace();
}
try {
fileWriter.append(sourceString);
bufferFileWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
}
and this is outPut file where i am just converting it to uppercase .
https://www.dropbox.com/s/yecq0wfeao672hu/RealTextCypher%20copy_replaced.txt?dl=0
hope this helps!
EDIT 2
If u are still looking for something ..you can also try STRINGWRITER
syntax would be
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer, "UTF-8");
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String theString = writer.toString();
i have an text file in my assets folder called test.txt. It contains a string in the form
"item1,item2,item3
How do i read the text into and array so that I can then toast any one of the three items that are deliminated by a comma
After reading post here the way to load the file is as follows
AssetManager assetManager = getAssets();
InputStream ims = assetManager.open("test.txt");
But cant work out how to get into an array
your help is appreciated
Mark
This is one way:
InputStreat inputStream = getAssets().open("test.txt");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] myArray = TextUtils.split(byteArrayOutputStream.toString(), ",");
Here is a sample code :
private void readFromAsset() throws UnsupportedEncodingException {
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("your_path/your_text.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line = "";
try {
while ((line = reader.readLine()) != null) {
//Read line by line here
}
} catch (IOException e) {
e.printStackTrace();
}
}
I am trying to read a CSV file using BufferedReader in android. My program works perfectly fine in Java but when I try read those data from Android following error I get.
01-31 17:09:58.466: W/System.err(15912): java.io.FileNotFoundException:
/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv: open failed: ENOENT (No
such file or directory)
Following code I am using here.
public double getLongitudes() {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
double longitudes = 0;
try {
br = new BufferedReader(
new FileReader(
"/Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv"));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
longitudes = Double.parseDouble(country[5]);
Log.d("worked", "worked");
// System.out.println("Latitude " + longitudes);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
return (longitudes);
}}
Any idea why its happening ??
The path /Users/sabbir/Documents/workspace/TestCSV/src/file/input.csv is invalid. This looks like the path to a file on your computer rather than your Android device. You need to push the file to your device or your emulated device and access it from there. Even the Android emulator will not read files directly from your computer's filesystem.
Proper way to store your CSV in Android is:
("/sdcard/Android/data/filename.csv");
The .csv file needs to be in your project resources. You can copy the file into assets folder and read it this way
AssetInputStream asset_stream = (AssetInputStream)getAssets().open("input.csv");
InputStreamReader reader = new InputStreamReader(asset_stream);
BufferedReader br = new BufferedReader(reader);
This is one method that has worked for me before.
Another method would be to put the file into res/raw folder and access it
InputStream file = getResources().openRawResource(R.raw.inputfile);
You can also refer to https://stackoverflow.com/a/3851429/3092829
Hope this helps!
So i have solved my problem.
public class ReadCSV {
BufferedReader br = null;
String line = "";
String cvsSplitBy = ";";
String[] nextLine;
String[] country;
AssetInputStream asset_stream = null;
public String[] getLatitude() {
try {
asset_stream = (AssetInputStream) MainActivity.getContext()
.getAssets().open("Input.csv");
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader reader = new InputStreamReader(asset_stream);
Log.d("logg", "log" + reader);
br = new BufferedReader(reader);
Log.d("logg", "log" + br);
try {
while ((line = br.readLine()) != null) {
country = line.split(cvsSplitBy);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return country;
}
As you can see I am trying to get my latitude by returning it through country. But when I trying get it from another fragment class through this,
String[] lat;
lat = csv.getLatitude();
Log.d("", "" + lat);
Why I don't get latitude back ?