This is my method for reading a txt file in the raw folder:
public static String readTextFile(Activity activity,int rawId){
InputStream inputStream = activity.getResources().openRawResource(rawId);
System.out.println(inputStream);
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();
}
return byteArrayOutputStream.toString();
}
My code for equal :
String read_text= partsViewModel.getImageAddress().trim();// read_text is dc18b7f823e94dcb85a5f38845300324
if (read_text.equals("dc18b7f823e94dcb85a5f38845300324")) {
// equal
} else {
// not equal
}
Why is read_text not equal with dc18b7f823e94dcb85a5f38845300324 ?
if your file in raw folder is a different encoding, you may not get a true from equals().
you need to watch out byteArrayOutputStream.toString(), try
byteArrayOutputStream.toString("ISO-8859-1")
or
byteArrayOutputStream.toString("utf-8")
Also, your code is
partsViewModel.getImageAddress().trim()
you should also make sure if it is actually come from your readTextFile code.
Related
I choose a text file from internal storage of Android e.g Sample.txt that convert the file to byte array using convertFileToByteArray( Uri documentUri)
Context applicationContext = MainActivity.getContextOfApplication();
private byte[] convertFileToByteArray(Context context, Uri documentUri) {
ByteArrayOutputStream buffer = null;
try {
InputStream inputStream = applicationContext.getContentResolver().openInputStream(documentUri);
int nRead;
byte[] data = new byte[16384];
buffer = new ByteArrayOutputStream();
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
} catch (Exception e) {
e.getLocalizedMessage();
}
return buffer.toByteArray();
}
In this line
InputStream inputStream = applicationContext.getContentResolver().openInputStream(documentUri);
no catch on exception error however, it catch Exception and return "No such directory" when I choose a file that cannot be identified their extension type, for example, Sample.lev1, Sample.abc, Sample.rty
This android app is for encryption and decryption, so my extension for encrypted file would be weird, such as, .lev1, .abc, .rty.
Encryption are fine because I choose a file that can be readable (.txt, .pdf) but decryption no because when trying to convert file(.lev1, .abc, .rty) to byte array, it throws "FileNotFoundException",
case R.id.btnGO://WILL CRYPT file
Uri doctUri = chosenFile;
keyType = MainActivity.keyType;
if (keyType == null || doctUri == null || radioGroup.getCheckedRadioButtonId() == -1) {
setMessage("Selection not Complete !");
} else {
mimeType = getMimeType(getContext(), doctUri);//check file whether it suitable or not.
// and to be used for save file
if (functionCode == ENCRYPT_FILE) {
try {
if (mimeType == null || isBCDMimeType(getFileName(doctUri))) {
if (isBCDMimeType(getFileName(doctUri))) {
//
} else {
}
} else {
byte[] b = convertFileToByteArray(doctUri);
launchRingDialogForEF(null, b, mimeType, keyType);
}
} catch (Exception e) {
e.getLocalizedMessage();
}
} else if (functionCode == DECRYPT_FILE) {
if (isVendorMimeType(getFileName(doctUri))) {
try {
byte[] b = convertFileToByteArray(doctUri);
size = b.length;
encryptDecryptHex ead = new encryptDecryptHex();
ead.decrypt(usbDeviceConnection, epOUT, epIN, b);
returnEData = ead.deData;
output = ead.decryptedData;
showMessageAfterTryToCrypt(returnEData, output, "Decrypt File", ead.m, ead.k);//m= mimeType k=keyType
goOk(usbDeviceConnection, epOUT, epIN);
} catch (Exception e) {
e.getLocalizedMessage();
}
} else {
}
}
}
You have get the permission at runtime before accessing any device storage if the os version is 6.0 and more. Check the following official documentation for more information
https://developer.android.com/training/permissions/requesting.html
the uri for Encrypted.ab(for example) was appended by "%00"
content://com.android.externalstorage.documents/document/primary%3AEncrypted.a%00b%00%00%00%00%00
I need when app starts, to check if file exists, if not to be created..
I need a block of code to append files into it
than I need a block of code that read that text line by line
than to remove a line ....
I found this code at stackoverflow, and they said that the file will be created in that location...
//Here I have this :
//Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
//
String filePath = "/data/data/com.example.myapp/files/text.txt";
File file = new File(filePath);
if(file.exists()){
//Do nothing
}
else{
try {
final String TESTSTRING = new String("");
FileOutputStream fOut = openFileOutput("text.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(TESTSTRING);
osw.flush();
osw.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
}
}
To add Lines in text I made this :
private void write(){
S ="/data/data/com.example.myapp/files/text.txt";
try {
writer = new FileWriter(S, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
writer.write(emri.getText().toString() + "\n" + link.getText().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And when I have to read them :
public class PlayList extends ListActivity {
ArrayList<String> listaE = new ArrayList<String>();
ArrayList<String> listaL = new ArrayList<String>();
InputStream instream;
int resh=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lexo();
String[] mStringArray = new String[listaE.size()];
mStringArray = listaE.toArray(mStringArray);
setListAdapter(new ArrayAdapter<String>(PlayList.this,android.R.layout.simple_list_item_1,mStringArray));
}
private void lexo(){
String S ="/data/data/com.example.myapp/files/text.txt";
try {
// open the file for reading
instream = new FileInputStream(S);
// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
do {
line = buffreader.readLine();
if ((resh % 2) == 0) {
listaL.add(line);
}
else {
listaE.add(line);
}
// do something with the line
} while (line != null);
}
} catch (Exception ex) {
// print stack trace.
} finally {
// close the file.
try {
instream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code does not work at all, and is missing the code to remove a line..
So everything I need is :
Code to write into file ( file to be saved because will be used until the app will be installed )
Code to read that file line by line ( so to be added in array, odd lines in one array, other lines in another array )
Code to remove a line from that file ( array to be added in listview and when user touches the line, touched line to be removed )
To add lines on list-activity
Any help will be very very appreciated,
Thanks...
First of all, you should use .getFilesDir().getPath() on your app's context, instead of hardcoding the path. That's commented in your first block. Second, create an OutputStream like this:
OutputStream out = new FileOutputStream(filePath);
If you have an InputStream called in, you'll be able to write it to a file using this code:
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
in.close();
out.close();
When you do create a file, check the rest (I didn't look) and get back to StackOverlow, if it fails. Don't make any of us do all the work, okay? Rip it to small part and make an effort.
Good luck with your work.
I am using RetrieveFilestream method with BufferedInputStream in a for loop. I am closing all
streams after processing each file and also adding ftp complete pending command.
Every thing works as expected in my test environment with few files. But in realtime data where there are 200-300 files, it hangs somewhere.
It is not throwing any exception making it difficult to debug. Cannot debug one by one. Any help?
Here is my code Block.
public String LoopThroughFiles(FTPClient myftp, String DirectoryName)
{
boolean flag=false;
String output="";
InputStream inStream=null;
BufferedInputStream bInf= null;
StringBuilder mystring = new StringBuilder();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
try {
flag= myftp.changeWorkingDirectory(DirectoryName);
if(flag==true)
{
FTPFile[] files = myftp.listFiles();
progressBar.setMax(files.length);
String fname="";
myftp.enterLocalPassiveMode();
if(files.length > 0)
{
int n=0;
for (FTPFile file : files)
{
n=n+1;
int r= progressBar.getProgress();
progressBar.setProgress(r+n);
fname=file.getName();
// String path= myftp.printWorkingDirectory();
if(fname.indexOf("txt") != -1)
{
inStream = myftp.retrieveFileStream(fname);
int reply = myftp.getReplyCode();
if (inStream == null || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {Log.e("error retrieving file",myftp.getReplyString()); }
bInf=new BufferedInputStream (inStream);
int bytesRead;
byte[] buffer=new byte[1024];
String fileContent=null;
while((bytesRead=bInf.read(buffer))!=-1)
{
fileContent=new String(buffer,0,bytesRead);
mystring.append(fileContent);
}
mystring.append(",");
bInf.close();
inStream.close();
boolean isSucess= myftp.completePendingCommand();
if(isSucess == false)
Log.e("error retrieving file","Failed to retrieve the stream for " + fname);
}
}
flag= myftp.changeToParentDirectory();
}
}
}
catch (java.net.UnknownHostException e) {
e.printStackTrace();
Log.e("readfile,UnknownHost",e.getMessage());
}
catch (java.io.IOException e) {
e.printStackTrace();
Log.e("readfile,IO",e.getMessage());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,General",e.getMessage());
}
finally
{
try {
output = mystring.toString();
if(bInf != null)
bInf.close();
if(inStream != null)
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,finallyblock",e.getMessage());
}
}
return output;
}
There is Arabic encoded pdf file that is received from a server via a web service in my Android application, then I decode it and save it to be cashed to open it anytime,this is the file I download_which also is encoded_ the problem is the file became not searchable anymore, this is the code I use to decode the file:
protected Void doInBackground(String... myLink) {
if (conDetector.isConnectingToInternet()) {
File myDir = getFilesDir();
String fileName = PDFCACHE;
File cachedFile = new File(myDir, fileName);
// to check if the cached file in the memory or not
if (cachedFile.exists()) {
try {
readPDFFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (!cachedFile.exists()) {
try {
URL url = new URL(myLink[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_size = urlConnection.getContentLength();
source = new BufferedInputStream(url.openStream(), 8192);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buffer = new byte[1024];
long total = 0;
int count = 0;
// buffer=new
// Scanner(source).useDelimiter("\\A").next().getBytes();*/
// buffer = Base64.decode(buffer, 0);
for (int i; (i = source.read(buffer)) != -1;) {
total += i;
bos.write(buffer, 0, i); // no doubt here is 0
publishProgress(""
+ (int) ((total * 100) / file_size));
}
if (flag == false) {
bytes = bos.toByteArray();
bytes = Base64.decode(bytes, Base64.DEFAULT);
String decodedString = new String(bytes);
if (bytes != null) {
openBuffer(bytes);
if (manipulateCache())
try {
savePDFFile(bytes);
// source.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
core = openFile(decodedString);
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// when there is no internet connection "offline mode"
} else if (!(conDetector.isConnectingToInternet())) {
if (!PDFCACHE.equals(null)) {
try {
readPDFFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
} }
The file you received is not searchable, the font objects contain ToUnicode maps claiming most of the glyphs used are numbers, symbols, or Latin characters which does not match their appearance as Arabic characters.
Thus, no standard PDF viewer can be used to search the files.
My code is below:
I am not able to use a string in the file name. Any suggestions?
If i use R.raw.anyString , it shows error
tv3.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.filname);
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();
}
return byteArrayOutputStream.toString();
}
This code works great for me:
InputSource inputSource = new InputSource(ApplicationContext.get()
.getResources().openRawResource(R.raw.countries));
i use it to open XML file and parse it later on i my code.