Подтвердить что ты не робот

Файл Android FileInputStream для чтения() в String

Любые эксперты, которые могут мне помочь? В моей основной деятельности Android я пытаюсь сохранить String в файл, а затем получить его, если пользователь установил его раньше. Не удалось найти каких-либо примеров, близких к тому, что я делаю. Я бы очень признателен за любую помощь! Вот мой тестовый пример:

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
       }
     }
 }
4b9b3361

Ответ 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() ;
    }

Ответ 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
        }
    }
}