Android Java读取和保存数据不起作用
Posted
技术标签:
【中文标题】Android Java读取和保存数据不起作用【英文标题】:Android Java Read and Save data doesnt work 【发布时间】:2014-06-09 13:01:53 【问题描述】:嘿,我想保存数据,然后我想阅读它们并将它们放入 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();
我可以改变什么?` 请帮帮我 我正在使用日食 我想保护 .txt 而不是外部的。
【问题讨论】:
您是否遇到任何错误?如果是这样,你能提供堆栈跟踪吗? :) 当我按下加载时,我得到 android.content.res.Resources$NotFoundException: String resource ID #0x0 【参考方案1】:我不相信您创建的文件正确:
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
块封装代码以捕获从这些对象抛出的IOException
。
编辑
将此添加到您的清单文件中:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
或者...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
希望对您有所帮助! :)
【讨论】:
private void read() try File myFile = new File("bla.txt"); FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader( new InputStreamReader(fIn)); for(int i= 0; i<=1; i++) if(i == 0) bla = Integer.parseInt(myReader.readLine()); if(i == 1) bla2 = Integer.parseInt(myReader.readLine()); myReader.close();
@user3722368 您在阅读之前正在创建一个新文件
我可以把我的完整项目发给你吗?
@user3722368 我无法为您执行此操作 :( 抱歉...但是此链接可能对您有所帮助 ***.com/questions/1239026/…
哦,我重新启动了模拟器,现在我可以保护数据了:)谢谢:)以上是关于Android Java读取和保存数据不起作用的主要内容,如果未能解决你的问题,请参考以下文章
从 InputStream 读取时,Android Socket BufferedReader readLine() 不起作用