我创建了写入和读取文件的应用程序。当我点击按钮时,我的文件是写的,也是在同一个按钮点击时读取文件。我想当我的文件写入时,该文件将其保存到SQLite中。我在网上冲浪很多但是可以'找到合适的来源或想法如何做到这一点。并将该文件与输入字符串比较,如“代码”。如果这个input_String与存储在SQLite数据库中的那个文件匹配,如果匹配用户无法继续进行进一步的处理。如果有人能够给我一些关于这个的建议,我将不胜感激。我希望其他人人们也觉得这很有用。这是我的代码。感谢高级。
活动类
public class Write extends Activity {
/** Called when the activity is first created. */
EditText myText;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
myText = (EditText) findViewById(R.id.myText);
Button createButton = (Button) findViewById(R.id.btnCreate);
Button readButton = (Button) findViewById(R.id.btnRead);
createButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
createFile(myText.getText().toString());
myText.setText("");
readFile();
}
});
}
private void createFile(String Text)
{
FileOutputStream fos = null;
try
{
fos = openFileOutput("mynote.txt", MODE_PRIVATE);
fos.write(Text.getBytes());
Toast.makeText(getApplicationContext(), "File created succesfully",
Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
catch (IOException e)
{
Log.e("CreateFile", e.getLocalizedMessage());
}
finally
{
if (fos != null)
{
try
{
// drain the stream
fos.flush();
fos.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
And the DataBase_Adapter code
//Table Name
public static final String TABLE_NAME_CODE="code_table";
//Colum,n Names
public static final String KEY_CODE_ID="ID";
public static final String KEY_CODE_NAME="USERNAME";
//Table Create Statement
public static final String DATABASE_CREATE_CODE = "CREATE TABLE "+TABLE_NAME_CODE+" ("+KEY_CODE_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+KEY_CODE_NAME+"TEXT)";
//Insert Code in Database code_table
public void saveCode(String strKey_Code)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(KEY_CODE_NAME , strKey_Code);
// Insert the row into your table
db.insert(TABLE_NAME_CODE, null, newValues);
}
答案 0 :(得分:0)
尝试将txt文件转换为byte [],然后将其保存在blob数据sqlite中。
InputStream is = new FileInputStream("txt file path");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
while ((int bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byte[] bytes = bos.toByteArray();
byte[] dataToSave = Base64.encode(bytes, Base64.DEFAULT);
将此dataToSave byte []保存到yout sqlite DB的blob数据列。
答案 1 :(得分:0)
你采取的方法可以稍微改进一下,考虑只在数据库中存储文件的名称,你已经保存了文件,对吧?为什么要将他们的内容再次存储在数据库中?