Android - Compare String with .txt file in raw folder - android

I want to know how to compare string value with .txt file's every line and get equal value.
I get All values from .txt file but i don't understand how to compare it.
For example
ABC
CBA
CCC
are in my .txt file,
and in my activity
String someText = "ABC";
and how to compare it with .txt file eacline.
I done below code to get .txt file values.
String result;
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.out);
byte[] b = new byte[in_s.available()];
in_s.read(b);
result = new String(b);
tx.setText(result);
} catch (Exception e) {
// e.printStackTrace();
result = "Error: can't show file.";
tx.setText(result);
}

BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("out.txt"), "UTF-8"));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();
while (mLine != null) {
//process line
//mLine = reader.readLine();
if ("ABC".equals(mLine)){
Toast.makeText(this, "Yuppppiiiiii", 1000).show();
}
mLine = reader.readLine();
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

I think that your problem is because the way you read the file.
you currently read all file content into a string and this makes you difficult to compare.
Ok, now is the procedures:
You open the file (Create an InputStream, use the Assert, and then wrap it inside a BufferedReader)
You read it line by line, store value in a variable (Use readline() function of bufferreader)
You call the compare string function for this variable and your string (String.equal)
I hope you can understand it clearly. All remain task are about the Android docs.

Related

java.lang.RuntimeException: java.util.zip.DataFormatException: incorrect header check

My target is to extract raw text from pdf file. I get the byte array but the content is encoded with FlateDecode algorithm. So I was trying to decode the raw content using this code
public String readTextFile(Uri uri){
String mSelectedFilePath = FileUtils.getPath(MainActivity.this,
uri);
Log.e(TAG," path "+mSelectedFilePath);
File sdcard = Environment.getExternalStorageDirectory();
StringBuilder text = new StringBuilder();
try {
File file = new File(mSelectedFilePath);
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
Log.e(TAG," line "+line + " "+startStream+" "+startDecode);
byte[] pText;
if(line.contains("FlateDecode")){
startDecode = true;
}
if(line.equals("stream")){
startStream = true;
continue;
}
if(line.equals("endstream")){
startDecode = false;
startDecode = false;
}
if(startDecode && startStream){
Log.e(TAG, " inside decode");
pText = FLATEDecode(line.getBytes());
}
else pText = line.getBytes();
String res = new String(pText,"UTF-8");
text.append(res);
text.append('\n');
Log.e(TAG,res);
}
br.close();
}
catch (IOException e) {
}
}catch (Exception e){
e.printStackTrace();
}
return text.toString();
code for decoding :
byte[] buf = new byte[1024];
Inflater decompressor = new Inflater();
decompressor.setInput(src);
// Create an expandable byte array to hold the decompressed data
ByteArrayOutputStream bos = new ByteArrayOutputStream(src.length);
try {
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
} catch (DataFormatException e) {
decompressor.end();
throw new RuntimeException(e);
}
decompressor.end();
return bos.toByteArray();`
But I am getting this error
Caused by: java.util.zip.DataFormatException: incorrect header check
java.util.zip.Inflater.inflateImpl(Native Method)
java.util.zip.Inflater.inflate(Inflater.java:237)
java.util.zip.Inflater.inflate(Inflater.java:214)
I know that I can use a library like itext or pdfbox , but the problem is these library doesn't work well with bangla pdf which is my final target. That's why I am trying to build a pdf content extractor from scratch. Here some the raw data I get from pdf. I want to decode it to get the original data.
3 0 obj
<</Type/Page/Parent 2 0 R/Resources<</Font<</F1 5 0 R>>/ProcSet[/PDF/Text/ImageB/ImageC/ImageI] >>/MediaBox[ 0 0 612 792] /Contents 4 0 R/Group<</Type/Group/S/Transparency/CS/DeviceRGB>>/Tabs/S/StructParents 0>>
endobj
4 0 obj
<</Filter/FlateDecode/Length 126>>
stream
x�S�P����u�tQ0��SprqVp
You don't want to use readLine() on the binary data. Once you've read the length (126) and the line with "stream", then you want to read 126 bytes of binary data (starting with the "x" in your example) and feed exactly that to inflate.

I can't read .txt files from the raw folder

I am trying to learn how basic operations work in android apps. I have a .txt file in row folder and I can't read anything. Because when I execute the code (although I don't get any logcat errors) after one second, the emulator turns into a black screen.
String str="";
InputStream is=getResources().openRawResource(R.raw.readme);
StringBuilder finalstring=new StringBuilder();
BufferedReader bf=new BufferedReader(new InputStreamReader(is));
try {
while(str!=bf.readLine()){
finalstring.append(str);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView tv=(TextView)findViewById(R.id.tvli);
tv.setText(finalstring);
Your while loop appears to be the problem. The condition in it doesn't really make sense. Try:
while((str = bf.readLine()) != null){
finalstring.append(str);
}
Your current loop will never run, as it will evaluate to "while str doesn't equal the line form my text file"
Replace your while statement with this:
while((str = bf.readLine()) != null) {
finalString.append(str);
}

how to import a contact name and number from csv file to android phone by programmatically

I am new to android i am in need to read a contact details as contact name and phone number form csv file and store it into android phone by pro grammatically please help any one .
thanks in advance
It's just a read and parse CSV file program that you need .
So you can do something like :
//--- If your input stream is `inpStrm` of the csv file :
BufferedReader reader = new BufferedReader(new InputStreamReader(inpStrm));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
date = RowData[0];
value = RowData[1];
// Now use "data" and "value" as you need to
}
}
catch (IOException ex) {
// ex.printStackTrace();
}
finally {
try {
inpStrm.close();
}
catch (IOException e) {
// e.printStackTrace();
}
}
Now contact name and phone number will be present in data and value. That's it i suppose .

Internal storage not being written

I'm trying to read from website url then write into device internal storage. Below are my code, the system output can print the line out but there is no file at internal storage.
Suppose the abc.xml will appear at "/data/data/my-package/abc.xml" but there is nothing...
Kindly help me on this problem.
try {
URL sourceUrl = new URL("mysite.php");
BufferedReader in = new BufferedReader(
new InputStreamReader(sourceUrl.openStream()));
String inputLine;
OutputStream out = openFileOutput("abc.xml", Context.MODE_PRIVATE);
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.write(inputLine.getBytes());
}
in.close();
out.close();
}
catch (IOException e) {
Log.d(LOG_TAG, e + "");
}
I wrote a simple function that saves a user object to the internal storage. The code works and seems like same you wrote above except 1 difference. I also add 1 more catch statement which is the following
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
Log.e(LOGTAG, e1.toString());
return false;
}
I know it won't solve the problem but at least you may find out why it doesn't work if the program throws a FileNotFoundException

Reading and writing to the file Android

I am learning Android and I am making some basic math program(game). It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can. If you solve problem u get 1 point.
Anyway right now, I want to get number of points that user have made, and write it to the file, and later to read it ( for now just to log it).
When I click to button to write file, it does and I get this log message:
09-21 21:11:45.424: DEBUG/Writing(778): This is writing log: 2
Yeah, seems that it writes. Okey, lets read it.
09-21 21:11:56.134: DEBUG/Reading log(778): This is reading log:2
It reads it.
But when I try again to write, it seems that it will overwrite previous data.
09-21 21:17:19.183: DEBUG/Writing(778): This is writing log: 1
09-21 21:17:28.334: DEBUG/Reading log(778): This is reading log:1
As you can see it reads just last input.
Here it is that part of code, where I am writing and reading it.
public void zapisi() {
// WRITING
String eol = System.getProperty("line.separator");
try {
FileOutputStream fOut = openFileOutput("samplefile.txt",
MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(poenibrojanje+eol);
//for(int i=0;i<10;i++){
Log.d("Writing","This is writing log: "+poenibrojanje);
//}
//osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void citaj() {
// READING
String eol = System.getProperty("line.separator");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
openFileInput("samplefile.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
}
//TextView textView = (TextView) findViewById(R.id.result);
Log.d("Reading log","This is reading log:"+buffer);
System.out.println(buffer);
//tvRezultat.setText(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
You can use the openFileOutput ("samplefile.txt", MODE_APPEND)

Categories

Resources