嘿,我想保存数据,然后我想读取它们并将它们放入 EditText
speichern.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() { int bla; StringBuffer strInhalt = new StringBuffer(""); try { FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我可以改变什么?` 请帮助我 我正在使用 eclipse 我想保护 .txt,而不是外部的。
最佳答案
我认为您没有正确创建文件:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
并读取此文件:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
并且不要忘记使用 try-catch
block 封装代码以捕获从这些对象抛出的 IOException
。
编辑
将其添加到您的 list 文件中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
或者...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
希望有帮助! :)
关于java - Android Java 读取和保存数据不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24120893/