2016-06-03 4 views
0

나는 많은 다른 코드를 시도했지만 아무 것도 작동하지 않습니다. .파일에 사용자 정보 저장 및 해당 정보 가져 오기

public class WriteToFile { 

Vector<Account> massAccount = new Vector<>(); 

public File openFile(File path, String fileName) throws IOException { 
    File f = new File(path, fileName); 
    f.createNewFile(); 
    return f; 
} 

public String getFileData(File f) { 
    String res = ""; 
    res = f.getAbsolutePath() + "\n"; 
    res += f.length() + "\n"; 
    res += new java.util.Date(f.lastModified()); 
    return res; 
} 

public void writeToFile(File f, String data) throws IOException { 
    FileWriter fw = new FileWriter(f); 
    fw.write(data); 
    fw.close(); 
} 

public String readFromFile(File f) throws IOException { 
    FileReader fr = new FileReader(f); 
    int size = (int)f.length(); 
    char[] res = new char[size]; 
    fr.read(res); 
    return new String(res); 
} 

public void writeObject(File f, String user, String pass, String question, String answer, Vector<Account> mass) throws IOException { 
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); 
    Account acc; 
    acc = new Account(user, pass,question, answer); 
    out.writeObject(acc); 
    for (Account accou: mass){ 
     out.writeObject(accou); 
    } 

    out.close(); 
} 

public Object readObject(File f, String accName) throws IOException 
{ 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); 
    Account acc; 
    String res = ""; 
    try { 
     while(true) 
     { 
      acc = (Account) in.readObject(); 
      if(acc.getUsername().equals(accName)) 
      return acc; 
     } 
    } 
    catch(EOFException e) 
    { 
     res = res + "End Of Records"; 
    } 
    catch(ClassNotFoundException e){} 
    return res; 
} 

public Vector<Account> readAllObjects(File f) throws IOException{ 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); 
    Account acc; 
    String res = ""; 
    try{ 
     while(true){ 
      acc = (Account) in.readObject(); 
      massAccount.add(acc); 
     } 
    } 
    catch (EOFException e){ 
     res = res + "End of Records"; 
    } 
    catch (ClassNotFoundException e){ 

    } 
    return massAccount; 
} 
} 

와 내가 사용하는 이해 것과 :

임 사용자를 등록 할 수있는 간단한 응용 프로그램을 만들고 정보를 저장하고 로그인하는 데 사용하려고 나는 파일에 클래스 이름을 쓰기가 파일을 확인해야하지만, 그것은 어떤 식 으로든 작동하지 않습니다.

내가 새 파일을 만들고 여기에서 읽어보세요 예를 들어

:

public class RegisterActivity extends AppCompatActivity { 
private EditText user, pass, hint, hintans, confirm; 
private Button Regi; 
private String saveUser = "", savePass = "", saveHint = "", checkUser = "" , checkPass = "", saveAns = "", confirmpass = ""; 
private WriteToFile writeToFile; 
private File f; 
private Account AccInfo; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_register); 
    user = (EditText)findViewById(R.id.regUser); 
    pass = (EditText)findViewById(R.id.regPass); 
    Regi = (Button)findViewById(R.id.btncon); 
    hint = (EditText)findViewById(R.id.regHint); 
    hintans = (EditText)findViewById(R.id.hintAnswer); 
    confirm = (EditText)findViewById(R.id.btnConPass); 
    writeToFile = new WriteToFile(); 
    Regi.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      try { 
       File dir = getFilesDir(); 
       f = writeToFile.openFile(dir, "User.txt"); 
       saveUser = user.getText().toString(); 
       savePass = pass.getText().toString(); 
       saveHint = hint.getText().toString(); 
       saveAns = hintans.getText().toString(); 
       confirmpass = confirm.getText().toString(); 
       AccInfo = (Account)writeToFile.readObject(f,saveUser); 
       if(AccInfo.getUsername().equals(saveUser)) 
        Toasty("Username already Exists."); 
       if(savePass.equals("")) 
        Toasty("Cannot leave password line empty."); 
       else if(!savePass.equals(confirmpass)){ 
        Toasty("Passwords don't match!"); 
       } 
       else{ 
        writeToFile.readAllObjects(f); 
        writeToFile.writeObject(f, saveUser, savePass, saveHint, saveAns, writeToFile.readAllObjects(f)); 
        Toasty("You have successfully registered!"); 
        Intent i = new Intent(RegisterActivity.this, LoginActivity.class); 
        startActivity(i); 
       } 
      } 
      catch (IOException e){ 
       Log.d("Error", "Regi onclick"); 
      } 
     } 
    }); 
} 

private void Toasty(String word){ 
    Toast.makeText(RegisterActivity.this, word, Toast.LENGTH_SHORT).show(); 
} 

} 

난 항상 IOException를 얻을, 그래서 내 코드는 괜찮 추측하지만 메신저 파일을 사용하여 잘못된 일을 메신저.

도움이 될 것입니다.

감사

편집 : 나는 어쩌면 문제의 범위를 좁힐 수 있었다. 이 메서드를 호출하면;

AccInfo = (Account)writeToFile.readObject(f,saveUser); 

내가 얻을 :

public Object readObject(File f, String accName) throws IOException { 
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); 
    Account acc; 
    String res = ""; 
    try { 
     while(true) { 
      acc = (Account) in.readObject(); 
      if(acc.getUsername().equals(accName)) 
       return acc; 
     } 
    } 
    catch(EOFException e) { 
     return acc = new Account("Default","secretPass","",""); 
    } 
    catch(ClassNotFoundException e){} 
    return acc = new Account("Default","secretPass","",""); 
} 

그리고 그것은 첫 번째 줄을 가리키는 : 내가 뭘 메신저 아무 생각

ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)); 

로 연결

Regi onclick: null 
java.io.EOFException 
at libcore.io.Streams.readFully(Streams.java:83) 
at java.io.DataInputStream.readShort(DataInputStream.java:152) 
     atjava.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2061) 
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:371) 
at merccorp.worklist.WriteToFile.readObject(WriteToFile.java:69) 
at merccorp.worklist.RegisterActivity$1.onClick(RegisterActivity.java:55) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

잘못된. 그리고 코드의 양은 유감 스럽지만이 문제의 원인에 대해 극도로 당혹 스럽습니다.

다시 한번 감사드립니다!

+0

는 당신이 IOException가 얻을 스택 추적을 게시 할 수있는 이미 볼을보고, 간단한 adjustet 될 수 있을까? – JonasCz

+0

그리고 getFileData 메서드에서 StringBuilder를 사용해야합니다. 예를 들어 ... Srings에서 concating을 호출하면 모든 concat은 새로운 String 개체를 만들고 다른 하나는 결과 (더하기 하나는 이전 값)에 추가합니다. StringBuilder를 사용하려고합니다. 마지막으로 toString()을 호출하여 문자열을 추가합니다. – Hrabosch

+0

Log.d 대신 IOException을 잡는 곳 ("Error", "Regi onclick"); Log.d를 시도하십시오 ("Error", e.getMessage()); 그렇게하면 틀린 것을 볼 수 있습니다. –

답변

0

사용자 정보 저장시 SQLite를 사용할 수 있습니다. 다시 액세스하기 쉽습니다.

DataBaseHelper.java

package com.techblogon.loginexample; 

import android.content.Context; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteDatabase.CursorFactory; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class DataBaseHelper extends SQLiteOpenHelper 
{ 
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
    { 
       super(context, name, factory, version); 
    } 
    // Called when no database exists in disk and the helper class needs 
    // to create a new one. 
    @Override 
    public void onCreate(SQLiteDatabase _db) 
    { 
      _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE); 

    } 
    // Called when there is a database version mismatch meaning that the version 
    // of the database on disk needs to be upgraded to the current version. 
    @Override 
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
    { 
      // Log the version upgrade. 
      Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data"); 

      // Upgrade the existing database to conform to the new version. Multiple 
      // previous versions can be handled by comparing _oldVersion and _newVersion 
      // values. 
      // The simplest case is to drop the old table and create a new one. 
      _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE"); 
      // Create a new one. 
      onCreate(_db); 
    } 

} 

LoginDataBaseAdapter.java

로그인에 가입

// get Instance of Database Adapter 
LoginDataBaseAdapter loginDataBaseAdapter=new LoginDataBaseAdapter(this); 
loginDataBaseAdapter=loginDataBaseAdapter.open(); 


// Save the Data in Database 
loginDataBaseAdapter.insertEntry(userName, password); 

를 들어

package com.techblogon.loginexample; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 

public class LoginDataBaseAdapter 
{ 
     static final String DATABASE_NAME = "login.db"; 
     static final int DATABASE_VERSION = 1; 
     public static final int NAME_COLUMN = 1; 
     // TODO: Create public field for each column in your table. 
     // SQL Statement to create a new database. 
     static final String DATABASE_CREATE = "create table "+"LOGIN"+ 
            "(" +"ID"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); "; 
     // Variable to hold the database instance 
     public SQLiteDatabase db; 
     // Context of the application using the database. 
     private final Context context; 
     // Database open/upgrade helper 
     private DataBaseHelper dbHelper; 
     public LoginDataBaseAdapter(Context _context) 
     { 
      context = _context; 
      dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 
     public LoginDataBaseAdapter open() throws SQLException 
     { 
      db = dbHelper.getWritableDatabase(); 
      return this; 
     } 
     public void close() 
     { 
      db.close(); 
     } 

     public SQLiteDatabase getDatabaseInstance() 
     { 
      return db; 
     } 

     public void insertEntry(String userName,String password) 
     { 
      ContentValues newValues = new ContentValues(); 
      // Assign values for each row. 
      newValues.put("USERNAME", userName); 
      newValues.put("PASSWORD",password); 

      // Insert the row into your table 
      db.insert("LOGIN", null, newValues); 
      ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show(); 
     } 
     public int deleteEntry(String UserName) 
     { 
      //String id=String.valueOf(ID); 
      String where="USERNAME=?"; 
      int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ; 
      // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show(); 
      return numberOFEntriesDeleted; 
     } 
     public String getSinlgeEntry(String userName) 
     { 
      Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null); 
      if(cursor.getCount()<1) // UserName Not Exist 
      { 
       cursor.close(); 
       return "NOT EXIST"; 
      } 
      cursor.moveToFirst(); 
      String password= cursor.getString(cursor.getColumnIndex("PASSWORD")); 
      cursor.close(); 
      return password;     
     } 
     public void updateEntry(String userName,String password) 
     { 
      // Define the updated row content. 
      ContentValues updatedValues = new ContentValues(); 
      // Assign values for each row. 
      updatedValues.put("USERNAME", userName); 
      updatedValues.put("PASSWORD",password); 

      String where="USERNAME = ?"; 
      db.update("LOGIN",updatedValues, where, new String[]{userName});    
     }  
} 

// fetch the Password form database for respective user name 
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName); 

// check if the Stored password matches with Password entered by user 
if(password.equals(storedPassword)) 
{ 
    //..... 
} 
else 
{ 
    //... 
} 
0

자신 만의 openFile(...)을 작성하면 안됩니다 (아마도 android persisntance article을 잘못 해석했을 수 있습니다). 대신 컨텍스트에서 미리 정의 된 방법을 사용하십시오. 활동은 Context의 하위 클래스이므로 직접 사용할 수 있습니다.

Context con = MyActivity.this; //Activity is subclass of Context 

//reading file content 
FileInputStream fis = con.openFileInput("myfilename.bin"); 

//writing file content 
int mode = Context.MODE_PRIVATE; // or Context.MODE_APPEND, see Context API 
FileOutputStream fos = con.openFileOutput("myfilename.bin", mode); 

//or 
//alternate solution 
File currentDir = con.getFilesDir(); 
File newFile = new File(currentDir, "myfilename.bin"); 

코드는 우리가

... 
Regi.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     try { 
      //File dir = getFilesDir(); not this way! 
      File dir = RegisterActivity.this.getFilesDir(); //but this way 
      //doing it this way you use the Context in a proper way 
      ... 
     }... 
    } 
}