How to create text file and insert data to that file on Android
Asked Answered
P

6

54

How can I create file.txt and insert data on file with content of some of variable on my code for example : population [][]; on Android, so there will be folder files on our package in file explorer (data/data/ourpackage/files/ourfiles.txt) Thank You

Prosthodontics answered 16/11, 2011 at 13:3 Comment(0)
C
131

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()
Croydon answered 16/11, 2011 at 13:12 Comment(7)
I run it on emulator first actually, this code can work for the emulator? Thx uProsthodontics
may u explain to me what is String sFileName, String sBody for? ThxProsthodontics
hmm I think it works but where is the location of the file that we make ?Prosthodontics
Just a curiosity @Croydon .. what does this line do in your code ? importError = e.getMessage(); iError();Countrywide
Does sFileName contain the file extension?Creolacreole
If you have android 6.0 and more, make sure your target sdk in gradle file less than 22. Or you need to implement run time permissions.Bergsonism
Is there any way to protect the file from modification? I mean just allow the file to be read onlyFabricate
W
11

Check the android documentation. It's in fact not much different than standard java io file handling so you could also check that documentation.

An example from the android documentation:

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
Woollen answered 16/11, 2011 at 13:12 Comment(3)
I try this : File myfile = new File("genetic_algorithm.txt"); try { String string = "hello world!"; FileOutputStream fos = openFileOutput(myfile, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); } catch (Throwable t) { Log.e(TAG, "error"); } it still can't work >_<Prosthodontics
check your log for the exception you got. "it still can't work" isn't a good description of the problem. Based on error log we could be able to help you. This is standard Java IO handling so you might want to read some tutorials on that topic.Woollen
The MODE_PRIVATE setting overwrites a file if it already exists. If you want to append data to the file use MODE_APPEND :-)Aguayo
T
8

If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt


         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) 
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);


                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }
Themselves answered 12/1, 2016 at 6:46 Comment(0)
W
0
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

isn't enough.

Add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

MANAGE_EXTERNAL_STORAGE documentation : Manage all files

To activate this permission, instead of using an intent:

  • Go to your app settings
  • Go to Authorizations
  • There is "Storage" click on it
  • Change the authorization from "Media only" to "all files".

Glad I could help.

Warlord answered 18/3, 2023 at 13:32 Comment(0)
T
-1
First create a Project With PdfCreation in Android Studio

Then Follow below steps:

1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
        String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root + "/PDF");
        System.out.print(myDir.toString());
        myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
        try {
            PdfWriter.getInstance(document, new FileOutputStream(FILE));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } // Open Document for Writting into document
        document.open(); // User Define Method
        addMetaData(document);
        try {
            addTitlePage(document);
        } catch (DocumentException e) {
            e.printStackTrace();
        } // Close Document after writting all content
        document.close();

5.   public void addMetaData(Document document)
    {
        document.addTitle("RESUME");
        document.addSubject("Person Info");
        document.addKeywords("Personal, Education, Skills");
                document.addAuthor("TAG");
        document.addCreator("TAG");
    }
    public void addTitlePage(Document document) throws DocumentException
    { // Font Style for Document
        Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
        Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
                | Font.UNDERLINE, BaseColor.GRAY);
        Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
        Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
        Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
        prHead.setFont(titleFont); // Add item into Paragraph
        prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
        PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
        myTable.setWidthPercentage(100.0f); // Create New Cell into Table
        PdfPCell myCell = new PdfPCell(new Paragraph(""));
        myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
        myTable.addCell(myCell);
        prHead.setFont(catFont);
        prHead.add("\nName1 Name2\n");
        prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
        document.add(prHead);
        document.add(myTable);
        document.add(myTable); // Now Start another New Paragraph
        Paragraph prPersinalInfo = new Paragraph();
        prPersinalInfo.setFont(smallBold);
        prPersinalInfo.add("Address 1\n");
        prPersinalInfo.add("Address 2\n");
        prPersinalInfo.add("City: SanFran. State: CA\n");
        prPersinalInfo.add("Country: USA Zip Code: 000001\n");
        prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
        prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
        document.add(prPersinalInfo);
        document.add(myTable);
        document.add(myTable);
        Paragraph prProfile = new Paragraph();
        prProfile.setFont(smallBold);
        prProfile.add("\n \n Profile : \n ");
        prProfile.setFont(normal);
        prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
        prProfile.setFont(smallBold);
        document.add(prProfile); // Create new Page in PDF
        document.newPage();
    }
Thoroughgoing answered 3/2, 2017 at 8:48 Comment(1)
He asked how to create a Text file (.txt) and you are answering showing how to create a .pdf file. With a library...Flibbertigibbet
G
-1

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
strwrt=FileWriter(File("sdcard/${NamaFile}"))
strwrt.write(teks)
strwrt.close()

after that, you can access File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folders.

Gastrocnemius answered 8/5, 2020 at 7:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.