[英]Android: How can I write to a file and read it into an array afterwards
I want to find the average of a series of values that the user chooses, with the help of a RatingBar
.我想在
RatingBar
的帮助下找到用户选择的一系列值的平均值。 Each time the user presses a Button
, I want to write the value of the RatingBar
to a file.每次用户按下
Button
,我都想将RatingBar
的值写入文件。 But when I try to save the value, the new value overrides the old one in the file instead of appending the value.但是当我尝试保存该值时,新值会覆盖文件中的旧值,而不是附加该值。 I would prefer to save the file in the internal storage.
我更愿意将文件保存在内部存储中。
Afterwards, I want to fetch all the values and put them into a ArrayList
.之后,我想获取所有值并将它们放入
ArrayList
。 And calculate the average of all the values given.并计算所有给定值的平均值。
I started in C#, so it would be easy with WriteLine()
and ReadLine()
but writeline
does not exist (at least, I didn't find in my research) and in some situations, readline
is deprecated.我从 C# 开始,所以使用
WriteLine()
和ReadLine()
会很容易,但writeline
不存在(至少,我在研究中没有发现),并且在某些情况下,不推荐使用readline
。
I tried to do this:我试图这样做:
private void writeMyArray(double rate){
try{
FileWriter fileWritter = new FileWriter("test3",true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(Double.toString(rate));
bufferWritter.close();
}catch(IOException e){
e.printStackTrace();
}
private void readMyArray(ArrayList<String> list){
try {
InputStream inputStream = openFileInput("test3.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
while (true) {
String line = reader.readLine();
if (line == null) {
list.add("");
break;
}
list.add(line);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
When I press the button, with this code:当我按下按钮时,使用以下代码:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
rating = ratingbar.getRating();
writeToFile(Double.toString(rating));
writeMyArray(ratingbar.getRating());
button.setText(getText(R.string.obrigado) + "!" + readFromFile() + arraydays.get(0));// + media(Double.parseDouble(readMyArray()), Integer.parseInt(stackread())));
//button.setText(getText(R.string.obrigado)+"!");
//ratingbar.setEnabled(false);
// button.setEnabled(false);
}
});
I get this logcat error:我收到此 logcat 错误:
07-06 10:54:44.180 29840-29840/com.example.emilio.notification E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.emilio.notification, PID: 29840
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.emilio.notification.MainActivity$2.onClick(MainActivity.java:116)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
the write/read file method is for other purpose but working, so the problem is in my array code.写入/读取文件方法用于其他目的但有效,所以问题出在我的数组代码中。
The other file code其他文件代码
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("estrela.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("estrela.txt");
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ((receiveString = bufferedReader.readLine()) != null) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
} catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
I assume you are looking for three methods here.我假设您在这里寻找三种方法。 One that appends a
double
to a file, another reads the numbers to an ArrayList<Double>
, and the third calculates the average rating.一个将
double
精度附加到文件,另一个读取数字到ArrayList<Double>
,第三个计算平均评分。
Write:写:
public void writeToFile(double rate) throws IOException {
FileOutputStream fout;
fout = new FileOutPutStream("myfile.txt", true);
new PrintStream(fout).println(rate);
fout.close();
}
Read:读:
public List<Double> readFromFile() throws IOException {
List<Double> rateList = new ArrayList<Double>();
Scanner s = new Scanner(new FileInputStream("myfile.txt"), "utf-8");
while (s.hasNextLine()) {
rateList.add(Double.parseDouble(s.nextLine()));
}
return rateList;
}
Find average rating:查找平均评分:
public double findAverageRating(List<Double> rateList) {
double averageRating = 0;
for (double r : rateList)
averageRating += r;
return averageRating / rateList.size();
}
This means you can do the following in your button listener:这意味着您可以在按钮侦听器中执行以下操作:
writeToFile(ratingbar.getRating());
button.setText(findAverageRating(readFromFile()));
Your Logcat output already tells you, what is wrong.您的 Logcat 输出已经告诉您出了什么问题。 You call
arraydays.get(0)
, while arraydays seems to has a size of 0, but you are trying to get the first value out of it.您调用
arraydays.get(0)
,而arraydays的大小似乎为 0,但您正试图从中获取第一个值。 You are appending to a variable called list with list.add(line)
.您正在使用
list.add(line)
附加到名为list的变量。 That's all I understand.这就是我的理解。 Your code is unreadable though.
你的代码虽然不可读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.