【问题标题】:Android FileInputStream read() txt file to StringAndroid FileInputStream read() txt 文件到字符串
【发布时间】:2012-02-24 02:53:39
【问题描述】:

有没有专家可以帮助我?在我的 Android 主要活动中,我试图将一个字符串保存到一个文件中,然后如果用户之前设置过它,然后再检索它。找不到任何与我正在做的事情接近的例子。我将不胜感激任何帮助!这是我崩溃的测试用例:

String testString = "WORKS";
String readString;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    FileOutputStream fos;

    try {
        fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
        fos.write(testString.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();

    }

    File file = getBaseContext().getFileStreamPath("test.txt");

    if (file.exists()) {

        FileInputStream fis;

        try {
            fis = openFileInput("test.txt");
            fis.read(readString.getBytes());
            fis.close();

        } catch (IOException e) {
            e.printStackTrace();

        } 

        txtDate.setText(String.valueOf(readString));

       } else {
                     // more code
       }
     }
 }

【问题讨论】:

  • 为什么要使用文件?尝试使用SharedPreferences - 更少的代码和混乱。

标签: java android io


【解决方案1】:

试试这样的

    public void writeData ( String data ) {
        try {
            FileOutputStream fOut = openFileOutput ( "settings.dat" , MODE_WORLD_READABLE ) ;
            OutputStreamWriter osw = new OutputStreamWriter ( fOut ) ;
            osw.write ( data ) ;
            osw.flush ( ) ;
            osw.close ( ) ;
        } catch ( Exception e ) {
            e.printStackTrace ( ) ;
        }
    }

    public String readSavedData ( ) {
        StringBuffer datax = new StringBuffer("");
        try {
            FileInputStream fIn = openFileInput ( "settings.dat" ) ;
            InputStreamReader isr = new InputStreamReader ( fIn ) ;
            BufferedReader buffreader = new BufferedReader ( isr ) ;

            String readString = buffreader.readLine ( ) ;
            while ( readString != null ) {
                datax.append(readString);
                readString = buffreader.readLine ( ) ;
            }

            isr.close ( ) ;
        } catch ( IOException ioe ) {
            ioe.printStackTrace ( ) ;
        }
        return datax.toString() ;
    }

【讨论】:

  • 我认为这是一个比其他答案更好的解决方案。如果那里有一个非常大的文件并且您无法将整个文件读取到内存中,那么您可以更改 while 以逐行处理它。另一种解决方案不像这个那么容易改变。
  • 会不会是缺少datax.append (System.lineSeparator ());?而且StringBuilderStringBuffer 更有效率——除此之外:谢谢,非常有帮助。
【解决方案2】:

读取文件试试这个:

FileInputStream fis;
fis = openFileInput("test.txt");
StringBuffer fileContent = new StringBuffer("");

byte[] buffer = new byte[1024];

while ((n = fis.read(buffer)) != -1) 
{ 
  fileContent.append(new String(buffer, 0, n)); 
}

【讨论】:

  • 请帮帮我,第二行显示错误 openFileInput is undefined... 怎么办?
  • @someone_smiley - 你在哪里写这个代码行?是Activity的方法。所以要么把你的代码放在 Activity 中,要么用这个方法使用 Activity 的上下文..
  • 嗨@user370305 - 我的代码没有任何活动。它只是我打算设计以减轻某些任务的类。我会将文件路径作为参数从一个类(同样不是一个活动)发送给它,然后让方法完成剩下的工作。请建议我怎样才能做到这一点。感谢您的宝贵时间
  • 这是正确的吗?您不必在创建字符串之前考虑读取的字节数吗?像这样: while ((n = fis.read(buffer)) != -1) { fileContent.append(new String(buffer, 0, n)); }
  • (从复制此代码的答案中复制我的评论...)此代码中还有另一个错误。您一次读取 1024 个字节,并假设它们可以使用默认字符集转换为字符串,但 Android 上的默认字符集是 UTF8,这是一种可变长度编码。如果文件的第 1024 字节是 2 字节字符的开头(或 3 字节字符的第 1 或第 2 字节,等等),它将被替换为指示编码错误的标记字符,并且next 将被损坏。阅读文本时使用Reader,而不是InputStream,以避免出现此类错误。
【解决方案3】:

少即是多;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tvText = (TextView) findViewById(R.id.tvText);

        try {
            // Create File and Content
            String FILE_NAME = "hallo.txt";
            String content = "Hallo Welt!";

            FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
            fos.write(content.getBytes());
            fos.close();

            // Read File and Content
            FileInputStream fin = openFileInput(FILE_NAME);
            int size;
            String neuText = null;

            // read inside if it is not null (-1 means empty)
            while ((size = fin.read()) != -1) {
                // add & append content
                neuText += Character.toString((char) size);
            }
            // Set text to TextView
            tvText.setText(neuText);

        } catch (Exception error) {
            // Exception
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-13
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多