2015-05-10 8 views
0

Я пытаюсь сохранить данные в файл в android, и я не могу представить свою ошибку, я также пытаюсь ее прочитать.Чтение и запись файлов - Java и android

Обзор: Я получил 2 кнопки и editext

набираю что-то в тексте редактирования, а затем нажмите кнопку «Сохранить», чтобы сохранить файл (save_to_file функции). Когда я нажимаю «читать» кнопку (функция read_file) я получаю что-то вроде B [] @ 3213 Я последовал андроид учебник от here

Мой код:

package com.keddy.filetesting; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 

import java.io.FileInputStream; 
import java.io.FileOutputStream; 


public class MainActivity extends Activity { 

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


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    public void save_to_file(View view){ 
     try{ 
      String filename = "Myfile.txt"; 
      EditText buffer= (EditText)findViewById(R.id.editText); 
      String pureText= buffer.getText().toString(); 
      pureText += '\n'; 
      FileOutputStream fos = openFileOutput(filename , Context.MODE_APPEND); 
      fos.write(pureText.getBytes()); 
      fos.close(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 

    public void read_file(View view){ 
     try 
     { 
      String filename = "Myfile.txt"; 
      FileInputStream fis = openFileInput(filename); 
      int len = fis.read(); 
      byte[] buff = new byte[len]; 
      fis.read(buff,0,len); 
      EditText changeText = (EditText)findViewById(R.id.editText); 
      changeText.setText(buff.toString()); 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 

} 

я не могу, кажется, заметили мою ошибку, так как я внимательно следил за учебником, может быть, моя проблема в чтении?

ответ

2

Нет проблем с чтением - вы просто вызываете метод toString() самого буфера-объекта. Это не выводит его содержимое, а адрес его памяти.

Try призвание:

changeText.setText(new String(buff)); 

Кроме того, рассмотрит основные кодовый во время преобразования (см String-Doc). Если ваш файл довольно большой, немедленно прочитайте буфер и используйте StringBuilder, чтобы объединить показания.

+0

спасибо За то, что мы очень полезны и дружелюбны, я обманывал это, я новичок в Java. – Keddy1201

0
public void save_to_file() throws Exception 
{ 
    FileOutputStream fos = null; 

    try 
    { 
     String filename = "Myfile.txt"; 

     EditText buffer= (EditText)findViewById(R.id.editText); 

     String pureText= buffer.getText().toString() 

     pureText += "\n"; // double-quote 

     FileOutputStream fos = openFileOutput(filename , Context.MODE_APPEND); 

     fos.write(pureText); 

     // call 'flush' and 'close' in the finally clause 
    } 
    catch(Exception e) 
    { 
     throw e; 
     //e.printStackTrace(); 
    } 
    finally 
    { 
     if(fos != null) 
     { 
      try 
      { 
       fos.flush(); 
      } 
      catch(Exception e) 
      { 
       throw e; 
      } 
      finally 
      { 
       try 
       { 
        fos.close(); 
       } 
       catch(Exception e) 
       { 
        throw e; 
       } 
      } 
     } 
    } 
} 

public void read_file() throws Exception 
{ 
    FileReader fileReader = null; 

    try 
    { 
     String filename = "Myfile.txt"; 

     fileReader = new FileReader(openFileInput(filename)); 

     StringWriter stringWriter = new StringWriter(); 
     int len = -1; 

     char[] buff = new char[512]; 

     while((len = fix.read(buff)) != -1) 
      stringWriter.write(buff,0,len); 

     String fileContents = stringWriter.toString(); 

     EditText changeText = (EditText)findViewById(R.id.editText); 

     changeText.setText(fileContents); 
    } 
    catch(Exception e) 
    { 
     throw e; 
     //e.printStackTrace(); 
    } 
    finally 
    { 
     if(fileReader != null) 
     { 
      try 
      { 
       fileReader.close(); 
      } 
      catch(Exception e) 
      { 
       throw e 
      } 
     } 
    } 
} 
Смежные вопросы