Is it possible to open a .txt file or show the content of the .txt file in activity? I really need it for my project. In my project I'm making the expandablelistview which shows the unit at the parentlist and chapter in childlist. Once the child is selected the selected child will open the appropriate .txt file. Is it possible to do so. Please give some suggestions on it.
You can Have TextView to show text in Activity, to set text on TextView use method setText(CharSequence) method.
To Read Text from .txt file, use Following method:
FileInputStream fis=null;
final StringBuffer buffer= new StringBuffer();
try {
fis = openFileInput("fileName.txt");
DataInputStream dataIO = new DataInputStream(fis);
String strLine = null;
if ((strLine = dataIO.readLine()) != null) {
buffer.append(strLine);
}
dataIO.close();
fis.close();
}
catch (Exception e) {
}
Use
textView.setText(buffer.toString());
to show in Activity.
Yes.
You just need a File and read it. Just use the Commons IO library from apache.org
//file located directly on SD root.
File myFile = new File(Environment.getExternalStorageDirectory(), "file.txt");
String contents = FileUtils.readFileToString(myFile);
After that just use something like myTextView.setText(contents); to set the text to a TextView.
Download Commons IO library here.
i think showing an xml file with a textview in it and setting up the textview to show whatever you want to show will do the trick.
textview.setText(open file you want to read from here);
to open a file you should use the Buffered reader and IO streams.
Related
I am working on a pdf editor.
I have made my changes on pdf files with OpenPDF core that is based on iText
And I am viewing the Pdf file with AndroidPdfViewer
My problems are:
Adding new annotations like text or tags or icons into an existing pdf file. ( SOLVED )
Show new changes right after annotations added into pdf file.( SOLVED )
Convert user click into Pdf file coordinates to add new annotation based on user clicked location.
Get click event on added annotations and read meta data that added into that annotation , for ex: read tag hash id that sets on icon annotation. ( SOLVED )
Remove added annotation from PDF File.
Any help appreciated
UPDATE
========================================================================
Solution 1: Adding annotations
Here is my code snippet for adding icon annotation into existing pdf file.
public static void addWatermark(Context context, String filePath) throws FileNotFoundException, IOException {
// get file and FileOutputStream
if (filePath == null || filePath.isEmpty())
throw new FileNotFoundException();
File file = new File(filePath);
if (!file.exists())
throw new FileNotFoundException();
try {
// inout stream from file
InputStream inputStream = new FileInputStream(file);
// we create a reader for a certain document
PdfReader reader = new PdfReader(inputStream);
// get page file number count
int pageNumbers = reader.getNumberOfPages();
// we create a stamper that will copy the document to a new file
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(file));
// adding content to each page
int i = 0;
PdfContentByte under;
// get watermark icon
Image img = Image.getInstance(PublicFunction.getByteFromDrawable(context, R.drawable.ic_chat));
img.setAnnotation(new Annotation("tag", "gd871394bh2c3r", 0, 0, 0, 0));
img.setAbsolutePosition(230, 190);
img.scaleAbsolute(50, 50);
while (i < pageNumbers) {
i++;
// watermark under the existing page
under = stamp.getUnderContent(i);
under.addImage(img);
}
// closing PdfStamper will generate the new PDF file
stamp.close();
} catch (Exception de) {
de.printStackTrace();
}
}
}
Solution 2: Show new changes
Here is my code snippet for refreshing the view after adding annotation, I have added this into AndroidPdfViewer core classes.
public void refresh(int currPage) {
currentPage = currPage;
if (!hasSize) {
waitingDocumentConfigurator = this;
return;
}
PDFView.this.recycle();
PDFView.this.callbacks.setOnLoadComplete(onLoadCompleteListener);
PDFView.this.callbacks.setOnError(onErrorListener);
PDFView.this.callbacks.setOnDraw(onDrawListener);
PDFView.this.callbacks.setOnDrawAll(onDrawAllListener);
PDFView.this.callbacks.setOnPageChange(onPageChangeListener);
PDFView.this.callbacks.setOnPageScroll(onPageScrollListener);
PDFView.this.callbacks.setOnRender(onRenderListener);
PDFView.this.callbacks.setOnTap(onTapListener);
PDFView.this.callbacks.setOnLongPress(onLongPressListener);
PDFView.this.callbacks.setOnPageError(onPageErrorListener);
PDFView.this.callbacks.setLinkHandler(linkHandler);
if (pageNumbers != null) {
PDFView.this.load(documentSource, password, pageNumbers);
} else {
PDFView.this.load(documentSource, password);
}
}
Solution 4: Click on object in pdf
I have create annotations and set it to added image object, AndroidPdfViewer has an event handler, here is the example
#Override
public void handleLinkEvent(LinkTapEvent event) {
// do your stuff here
}
I will add other new solutions into my question, as update parts.
Here is my code snippet for adding text into pdf file,
Your code does not add text into an existing pdf file. It creates a new PDF, adds text to it, and appends this new PDF to the existing file presumably already containing a PDF. The result is one file containing two PDFs.
Concatenating two files of the same type only seldom results in a valid file of that type. This does works for some textual formats (plain text, csv, ...) but hardly ever for binary formats, in particular not for PDFs.
Thus, your viewer gets to show a file which is invalid as a PDF, so your viewer could simply have displayed an error and quit. But PDF viewers are notorious for trying to repair the files they are given, each viewer in its own way. Thus, depending on the viewer you could also see either only the original file, only the new file, a combination of both, an empty file, or some other repair result.
So your observation,
but this will replace with all of the Pdf file, not just inserting into it
is not surprising but may well differ from viewer to viewer.
To actually change an existing file with OpenPDF (or any iText version before 6 or other library forked from such a version) you should read the existing PDF using a PdfReader, manipulate that reader in a PdfStamper, and close that stamper.
For example:
PdfReader reader = new PdfReader("original.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("original-stamped.pdf"));
PdfContentByte cb = stamper.getOverContent(1);
cb.beginText();
cb.setTextMatrix(100, 400);
cb.showText("Text at position 100,400.");
cb.endText();
stamper.close();
reader.close();
In particular take care to use different file names here. After closing the stamper and the reader you can delete the original PDF and replace it with the stamped version.
If it is not desired to have a second file, you can alternatively initialize the PdfStamper with a ByteArrayOutputStream and after closing the stamper and the reader replace the contents of the original file with those of the ByteArrayOutputStream.
I have a file which is "content.txt". At the first, if the file doesn't exists, I will create it and write the detail in the file as
"123,abc"
Then If I want to update the "abc" to "abcd". I used below code. Now, my issue is that If I want to add more line which does not equal first field "123", then it will append in the file. However, it does not append in my file. What is happend in my code? Could you help me to fix it
This is example. First my file is empty. I put the String "123,abc" then the content in the file is
123,abc
Then I insert "abcd" to update the its second field. The content of file is
123,abcd
Now, I insert a new field 456,xyz which does not equal 123 then the file is
123,abcd
456,xyz
This is my code
String whole_content="123,abc";
String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+ "/" + "content.txt" ;
boolean flagdataempty=false;
File file = null;
try {
file =new File(filename);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
flagdataempty=true;
}
} catch (IOException e) {
e.printStackTrace();
}
String tempFilename=filepath+"/" + "content_temp.txt";
File tempFile = new File(tempFilename);
BufferedReader reader = null;
BufferedWriter writer =null;
boolean flagsearch=false;
try {
reader = new BufferedReader(new FileReader(file));
writer=new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
flagdataempty=false;
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String[] separated = trimmedLine.split(",");
String classID_out = separated[1].trim(); // this will contain data
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
flagsearch=true;
}
else
writer.write(currentLine + System.getProperty("line.separator"));
}
if(flagdataempty|!flagsearch) {
writer.write(whole_content + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(file);
Update: I done by using flag. It will set true if I find 123. Otherwise,I will write the new line. Thanks
I don't see the code actually trying to write the content you want to write, but give following code a try, as you want to add next text which does not contain 123 to the next line.
if(classID_out.equals("abc"))
{
currentLine=separated[0].trim()+","+"abcd";
writer.write(currentLine + System.getProperty("line.separator"));
}else{
Files.write(Paths.get("filepath+ "/" + "content.txt"), "\n456,xyz".getBytes(), StandardOpenOption.APPEND);
}
I would not recommend this kind of fashion to read and write data which would change over the time and you constantly will have a lot of hustle reading and writing the data to it,
the Best way would be is to write JSON or XML of a serialized way to the text file. it will remove the headache of dealing with low level functions as you would have your object populated thought GSON or Simple XML Framework.
In a case I would suggest have a ArrayList of object which will be written to the text file, read the text file and populate your ArrayList from that, and then try adding something to the arraylist, if it already exist it wont add to the arrylist and if does not exist it will add to the arrylist, after your work is done with the Arraylist, write that to the text file again
I am trying to write my first app for Android. I knew Java formerly but it has been a year or two since I used it.
I want to create a simple file in internal storage - I understand I do not have to set any permissions to create such a file?
Is it a .dat file I need if I want to save an ArrayList? Does Android require me to use file extension when creating it?
Even with just trying the basic file creation - checking for existence of file and then creating it if it does not exist - does not work. Can anyone tell me what I am doing wrong?
(I have commented out the attempt to read the ArrayList, as I cannot even create the file. Just trying the basic file creation.)
(Also, I have tried the code with "Shares.dat" instead of just "Shares" as filename, that didn't work either. I don't even know whether Android recognises .dat files and to be honest I am not 100% sure that is the file I need.)
(If by any chance anyone can help, I may not be able to test any solution until next weekend......)
As for the last but one line, originally it read 'context.getFileDir()' but my class extends ActionBarActivity and I found on internet a suggestion to change to this.getFileDir(). I got a null pointer warning when I used context.getFileDir()
file = new File("Shares");
if (file.exists()){
url.setText("File Exists");
/*try{
is = openFileInput("Shares");
oi = new ObjectInputStream(is);
details = (ArrayList<Action>)oi.readObject();//warning
oi.close();//need finally??
}
catch(Exception e){url.setText((e.getMessage()));}
url.setText(details.get(0).getAddresse());*/
}
else
{
try
{
**file = new File(this.getFilesDir(), "Shares");**
}
catch(Exception e){url.setText((e.getMessage()));}
}
If you want a reference to a file that's created in private storage, you'd want to use getFileStreamPath("shares.dat") instead of creating a new File object. File extension shouldn't matter, but it's a good practice to add a file extension to keep track for yourself what those files are for.
For example:
private boolean fileExists(Context _context, String _filename) {
File temp = _context.getFileStreamPath(_filename);
if(temp == null || !temp.exists()) {
return false;
}
return true;
}
Then, if you wanted to write to a file named "shares.dat" then you'd use openFileOutput("shares.dat", Context.MODE_PRIVATE). If you wanted to read in from that file, you'd use openFileInput("shares.dat").
// Read in from file
if(fileExists(this, "shares.dat")) {
FileInputStream fis = this.openFileInput("shares.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Action> actions = (ArrayList<Action>)ois.readObject();
ois.close();
}
// Write out to file
FileOutputStream fos = this.openFileOutput("shares.dat", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(actions);
oos.close();
All stream operations shown above have the ability to throw an IOException, so be sure to wrap that code in a try/catch block as needed.
I've been trying to do some research and learn android. I do not understand what the following code does.
public class LogFile extends Activity {
private final static String STORETEXT = "storetext.txt";
private TextView write log;
public void readFileInEditor() {
try {
InputStream in = openFileInput(STORETEXT);
if (in != null) {
InputStreamReader tmp = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(tmp);
String str;
StringBuilder buf = new StringBuilder();
while ((str = reader.readLine()) != null) {
buf.append(str + "\n");
}
in.close();
writelog.setText(buf.toString());
}
} catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
I don't understand how this method works. Is it reading a file that is referenced with STORETEXT? If it making a file, where is this file saved? And finally, how can I access the "storetext.txt" file so that I may send it using
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
in an email attachment? Thanks for helping me learn, I've been trying to do some research on this but I am having trouble understanding this concept. Any help is appreciated.
openFileInput() is used so the file resides in the app specific internal files dir. Use getFilesDir() to find the directory and then add the filename. But.... Other apps have no access to this private directory. So you first have to copy the file to a place where other apps have access.
This code is reading in a text file "storetext.txt" and then displaying the content of the file in a text view.
The InputStreamReader reads the file and the BufferedReader and the StringBuilder work together to create a long string that has all the contents of the file.
How you access this file to sent with an Intent will depend on where the file is. Is it outside of your app environment, like on the SD card? Or is it in a resource folder like res/raw/storetext.txt?
You'll have to use different methods of getting a reference to your file depending on the situation. Do you know where the file is?
Also, if you are looking to send a file using the intent
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File("/path/to/file")));
and the file you are trying to send is in the apps private directory, you must use a ContentProvider in order to let other apps(like the native email app) access your file that you wish to send.
Here's a link that was very helpful in helping me figure that out.
http://stephendnicholas.com/archives/974
I have one xml file called bkup.xml stored inside sdcard "/sdcard/bkup.xml".
For creating bkup.xml I have used xmlSerialization.
I want to retrieve data from that bkup.xml file.
I have seen many examples but almost most of them are using resource file and using URL as a resource. But no one have example of giving a path of sdcard file.
I don't know how to fetch data from that file and parse it.
Thanks in advance.
Any suggestion will be appreciated
Here is an complete example with source. You just to get the File using
File file = new File(Environment.getExternalStorageDirectory()
+ "your_path/your_xml.xml");
Then do the further processing.
UPDATE
If you need example for different types of XML Parsers you can download complete example from here.
Use the FileReader Object like this :
/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* #param aFile is a file which already exists and can be read.
* File file = new File(Environment.getExternalStorageDirectory() + "file path");
*/
static public String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
Also you need to add permission to access the SDCard on the device.