如何在Android上创建文本文件并将数据插入该文件

k7fdbhmy  于 2023-03-21  发布在  Android
关注(0)|答案(6)|浏览(189)

我如何创建file.txt并在文件中插入数据,其中包含一些变量的内容,例如:人口[][];在Android上,所以会有文件夹文件在我们的包在文件资源管理器(data/data/ourpackage/files/ourfiles.txt)谢谢

cld4siwp

cld4siwp1#

使用这段代码你可以写入SDCard中的一个文本文件。沿着,你需要在Android Manifest中设置一个权限。

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

这是密码:

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();
    }
}

在写入文件之前,您还必须检查您的SDCard是否已安装&外部存储状态是否为可写。

Environment.getExternalStorageState()
wgxvkvu9

wgxvkvu92#

检查android documentation,它实际上与标准的java io文件处理没有太大的不同,所以你也可以检查文档。
android文档中的一个例子:

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

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
eimct9ow

eimct9ow3#

如果你想创建一个文件,并写入和追加数据到它多次,然后使用下面的代码,它将创建文件,如果不存在,并将追加数据,如果它存在。

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();

            }
2j4z5cfb

2j4z5cfb4#

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

还不够。

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

管理外部存储文档:Manage all files
要激活此权限,而不是使用Intent:

  • 转到你的应用设置
  • 转到授权
  • 有“Storage”(存储),单击它
  • 将授权从“仅媒体”更改为“所有文件”。

很高兴我能帮上忙。

cqoc49vn

cqoc49vn5#

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: john_pit@gmail.com \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();
    }
r1zk6ea1

r1zk6ea16#

我在用Kotlin
只需在此处添加信息,您还可以通过执行此示例为应用程序创建私有目录之外的可读文件

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

之后,你可以访问文件管理器,并查找内部存储。文本1. txt将在那里下面的所有文件夹。

相关问题