android – 如何将数组写入内部存储上的文本文件?

android – 如何将数组写入内部存储上的文本文件?,第1张

概述我需要将一些数据作为文本文件存储内部存储器上. 例如下面,我有一个按钮,我想在每次单击按钮时将一些数据保存在文本文件中.我正在测试一个例子: http://developer.android.com/training/basics/data-storage/files.html import java.io.FileOutputStream;import android.os.Bundle; 我需要将一些数据作为文本文件存储在内部存储器上.
例如下面,我有一个按钮,我想在每次单击按钮时将一些数据保存在文本文件中.我正在测试一个例子:

http://developer.android.com/training/basics/data-storage/files.html

import java.io.fileOutputStream;import androID.os.Bundle;import androID.app.Activity;import androID.content.Context;import androID.vIEw.Menu;import androID.vIEw.VIEw;import androID.vIEw.VIEw.OnClickListener;import androID.Widget.button;public class MainActivity extends Activity implements OnClickListener {    button b;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        b = (button) findVIEwByID(R.ID.button1);    }    @OverrIDe    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main,menu);        return true;    }    @OverrIDe    public voID onClick(VIEw v) {        String filename = "myfile";        String string = "Hello World!";        fileOutputStream outputStream;        try {          outputStream = openfileOutput(filename,Context.MODE_APPEND);          outputStream.write(string.getBytes());          outputStream.close();        } catch (Exception e) {          e.printstacktrace();        }    }}

我只将“mode_private”更改为“mode_append”,所以我可以看到保存的文件,但是我找不到保存的文件,我甚至找不到文件应该保存的目录.

另外,更具体地说,我需要在文本文件中存储一个数字数组(比如i = {1,2,3}到output.txt).
如果你能帮助我,我将不胜感激.

解决方法 首先,您缺少按钮的setonClickListener.它应该是…
b = (button) findVIEwByID(R.ID.button1);b.setonClickListener(this);

“但是我找不到保存的文件,我甚至找不到保存文件的目录.”

getApplicationContext().getfilesDir()将告诉您文件的保存位置.

AndroID DOCS说……

Your app’s internal storage directory is specifIEd by your app’s package name in a special location of the AndroID file system.

要将数组存储在文件中,请尝试以下 *** 作…

String filename = "myfile";String[] numbers = new String[] {"1,3"};fileOutputStream outputStream;try {  outputStream = openfileOutput(filename,Context.MODE_APPEND);  for (String s : numbers) {        outputStream.write(s.getBytes());    }   outputStream.close();} catch (Exception e) {  e.printstacktrace();}
总结

以上是内存溢出为你收集整理的android – 如何将数组写入内部存储上的文本文件?全部内容,希望文章能够帮你解决android – 如何将数组写入内部存储上的文本文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1140951.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存