Android FileInputStream read() txt file to String

2022-09-01 12:22:28

有专家可以帮助我吗?在我的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
       }
     }
 }

答案 1

要读取文件,请尝试以下操作:

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

答案 2

试试这样的东西

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

推荐