I am trying below code to select pdf from directory and read its contents but its not working
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, PICKFILE_RESULT_CODE);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode) {
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
// String filePath = data.getData().getPath();
// textViewFilePath.setText("File : " + filePath);
// readFromPdf(filePath);
StringBuilder text = new StringBuilder();
String filePath = data.getDataString();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('n');
}
scanResults.setText(text + ".....");
}
catch (IOException e) {
//You'll need to add proper error handling here
e.printStackTrace();
}
}
break;
}
}
I am getting below exception
java.io.FileNotFoundException:
content:/com.android.providers.downloads.documents/document/2295: open
failed: ENOENT (No such file or directory)
You should open an InputStream like
InputStream is = getContentResolver().openInputStream(data.getData());
You should not try to use a reader or try to read lines.
Those do not make sense for a pdf file.
Related
I want to create a file in AppA and then be able to access it from AppB only. I am able to create the file via the DocumentProvider and then access it via StorageClient see examples here. How do I setup the permission on the file in AppA so that only AppB can access it?
Method for file creation in AppA
String s = "kv;ab\nkv1;cd";
try {
byte[] buffer = s.getBytes();
String filename = "myfile.txt";
System.out.println("filename="+filename);
FileOutputStream fos = getContext().openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(buffer);
fos.close();
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
Methods for File access in AppB
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
Uri pickerInitialUri= Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, READ_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
readFileExternalStorage();
}
public String readFileExternalStorage() {
String s = "";
Uri uri1 = Uri.parse("content://com.example.android.storageprovider.documents/document/root%3Amyfile.txt");
try {
InputStream ins = this.getBaseContext().getContentResolver().openInputStream(uri1);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int size;
byte[] buffer = new byte[1024];
while ((size = ins.read(buffer, 0, 1024)) >= 0) {
outputStream.write(buffer, 0, size);
}
ins.close();
buffer = outputStream.toByteArray();
s = new String(buffer);
System.out.println("output=" + s);
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
TextView textview = findViewById(R.id.textView);
textview.setText(s);
return "ok\n" + s;
}
Two probable options-
https://developer.android.com/guide/topics/permissions/defining
Use a shared encryption key with user based salt to encrypt and decrypt stored files on Android
I would like to select a pdf file from file manager in android and convert it to text so text to speech can read it. I'm following this documentation from android developer site; however, this example is for opening a text file. I'm using PdfReader class/ library in order to open the file and convert to text. but I don't know how to integrate that with Uri.
Here's the code I need to convert from pdf to text using PdfReader
PdfReader pdfReader = new PdfReader(file.getPath());
stringParser = PdfTextExtractor.getTextFromPage(pdfReader, 1).trim();
pdfReader.close();
I'm calling file manager using intent so the user can select a pdf file
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
startActivityForResult(intent, READ_REQUEST_CODE);
}
});
then I'm getting uri and opening file
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
if(resultData != null) {
Uri uri = resultData.getData();
Toast.makeText(MainActivity.this, filePath , Toast.LENGTH_LONG).show();
readPdfFile(uri);
}
}
}
private String readTextFromUri(Uri uri) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream =
getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
return stringBuilder.toString();
}
public class SyncPdfTextExtractor {
// TODO: When you have your own Premium account credentials, put them down here:
private static final String CLIENT_ID = "FREE_TRIAL_ACCOUNT";
private static final String CLIENT_SECRET = "PUBLIC_SECRET";
private static final String ENDPOINT = "https://api.whatsmate.net/v1/pdf/extract?url=";
/**
* Entry Point
*/
public static void main(String[] args) throws Exception {
// TODO: Specify the URL of your small PDF document (less than 1MB and 10 pages)
// To extract text from bigger PDf document, you need to use the async method.
String url = "https://www.harvesthousepublishers.com/data/files/excerpts/9780736948487_exc.pdf";
SyncPdfTextExtractor.extractText(url);
}
/**
* Extracts the text from an online PDF document.
*/
public static void extractText(String pdfUrl) throws Exception {
URL url = new URL(ENDPOINT + pdfUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("X-WM-CLIENT-ID", CLIENT_ID);
conn.setRequestProperty("X-WM-CLIENT-SECRET", CLIENT_SECRET);
int statusCode = conn.getResponseCode();
System.out.println("Status Code: " + statusCode);
InputStream is = null;
if (statusCode == 200) {
is = conn.getInputStream();
System.out.println("PDF text is shown below");
System.out.println("=======================");
} else {
is = conn.getErrorStream();
System.err.println("Something is wrong:");
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
}
------------------------------------
Copying above code follow below Steps-
Specify the URL of your online PDF document on line 20.
Replace the Client ID and Secret on lines 10 and 11 if you have your own credentials.
use this
Gradle :-
implementation 'com.itextpdf:itextg:5.5.10'
try {
String parsedText="";
PdfReader reader = new PdfReader(yourPdfPath);
int n = reader.getNumberOfPages();
for (int i = 0; i <n ; i++) {
parsedText = parsedText+PdfTextExtractor.getTextFromPage(reader, i+1).trim()+"\n"; //Extracting the content from the different pages
}
System.out.println(parsedText);
reader.close();
} catch (Exception e) {
System.out.println(e);
}
I'm trying to select text file by open file explorer then read the selected file.
I tried many many solutions. the last one is this code
public void btnRead_Click(View view) {
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("text/plain");
startActivityForResult(chooseFile, 1);
}
#Override
protected void onActivityResult(int requestedCode, int resultCode, Intent data) {
if (requestedCode == 1) {
if (resultCode == RESULT_OK) {
File file = new File(data.getDataString());
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e){}
textView = (TextView) findViewById(R.id.textView);
textView.setText(text);
}
}
}
Thanks in advance
I found the solution here: https://stackoverflow.com/a/40638366/5727559
The code is:
public static int PICK_FILE = 1;
public void btnRead_Click(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/plain");
startActivityForResult(intent, PICK_FILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE)
{
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
String fileContent = readTextFile(uri);
Toast.makeText(this, fileContent, Toast.LENGTH_LONG).show();
}
}
}
private String readTextFile(Uri uri)
{
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try
{
reader = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri)));
String line = "";
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
reader.close();
}
catch (IOException e) {e.printStackTrace();}
return builder.toString();
}
i am trying to pick an audio file and save it , but i am getting ENOENT , yet i use the same code with image and it works fine !!!!! \n
i am using file provider to create/save files and it works more than probably .
how can the same code work with images yet not with audio : \n
here is some code examples \n
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0 && resultCode == RESULT_OK) {
Uri resultUri = data.getData();
saveFile(resultUri);
}
}
and to save the file i use :
File dirPath = new File(Environment.getExternalStorageDirectory(),"Moch/WAR/");
File file = new File(dirPath, "notification.mp3");
String sourceFilename = resultUri.getPath();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
if(!file.exists())
if (!file.createNewFile())
Toast.makeText(notificationsSettings.this,"Unable to make sound File",Toast.LENGTH_LONG).show();
if(file.exists()) {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(file, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != -1);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
mProgressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and this is the doomed error line : \n
/document/audio:266: open failed: ENOENT (No such file or directory)
I want to copy the pdf file from URL to and save the pdf file content in bitmap.
I have used following code but I am not getting the as it is content of pdf. It is giving something in different format.Please help me and tell me where I am wrong.
public class MyActivity extends ListActivity implements OnClickListener
{
Button addResumeFromUrlBtn;
EditText addResumeFromUrlTxt;
String resume;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.resumeselection);
addResumeFromUrlTxt = (EditText)findViewById(R.id.addResumeFromURLTxt);
addResumeFromUrlBtn = (Button)findViewById(R.id.addResumeFromURLBtn);
addResumeFromUrlBtn.setOnClickListener(this);
}
public String readPDF() throws Exception
{
BufferedReader in = null;
String page = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.inkwelleditorial.com/pdfSample.pdf"));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
page = sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {e.printStackTrace();}
}
}
return page;
}
public void onClick(View v)
{
if(v == addResumeFromUrlBtn)
{
try {
resume = readPDF();
} catch (Exception e)
{
e.printStackTrace();
}
RelativeLayout l = (RelativeLayout)findViewById(R.id.resumeRelativelayout);
TextView txt = new TextView(this);
txt.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
txt.setDrawingCacheEnabled(true);
txt.setText(resume);
txt.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
txt.layout(0, 0, txt.getMeasuredWidth(), txt.getMeasuredHeight());
txt.setDrawingCacheEnabled(false);
l.addView(txt);
}
}
}
Thanks
Monali
File file = new File(fileLocation);
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW); //Set Intent action view pdf file
intent.setDataAndType(path, "application/pdf"); //Set data type
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent); //Start Activity
} catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
This is the for display pdf
First of there is no support for pdf in Android so you need to open in some other app like adob or if you want to do it right way then need make the load lib like vudroid and apdfviewer .
apdfviewer is very good but there is no support how to compile source code, actually all lib work with c++ in backend so you need to install the ndk.
Vudroid is slow but you can compile easily.
I hope this will help you.