我在下面的代码中读取了下一行直到未编号文件的末尾(文件中的行没有数字)并且它完全正常。现在,我想读取前面的行(向后读取)。如果可能的话,随机播放(读取随机行)。任何想法。
这是一个例子:
InputStream in;
BufferedReader reader;
String qline;
try {
in = this.getAssets().open("quotations.txt");
reader = new BufferedReader(new InputStreamReader(in));
qline = reader.readLine();
quote.setText(qline);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在我的onClick方法中,我有一个下一个按钮
//code
else if (v.getId() == R.id.next) {
try{
if (( qline = reader.readLine()) != null) {
// myData = myData + qline;
quote.setText(qline);
}
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else if (v.getId() == R.id.back) {
// code for the back option
}
答案 0 :(得分:1)
您可以使用我的库FileReader,或修改它以适合您寻求的功能:
// FileReader, Khaled A Khunaifer
public class FileReader
{
public static ArrayList<String> readAllLines (String path)
{
ArrayList<String> lines = new ArrayList<String>();
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = br.readLine()) != null)
{
lines.add(line);
}
}
catch (Exception e)
{
e.printStackTrace()
}
return lines;
}
// NOTE: LINE NUMBERS START FROM 1
public static ArrayList<String> readLines (String path, long from, long to)
{
ArrayList<String> lines = new ArrayList<String>();
long k = 1;
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
do
{
line = br.readLine(); // read line k
if (k >= from)
{
if (k > to) break; // STOP
lines.add(line);
}
k++;
}
while (line != null);
}
catch (Exception e)
{
e.printStackTrace()
}
return line;
}
// NOTE: LINE NUMBERS START FROM 1
public static String readLine (String path, long i)
{
long k = 1;
InputStream fis;
BufferedReader br;
String line;
try
{
fis = new FileInputStream(path);
br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
do
{
line = br.readLine(); // read line k
if (k == i)
{
break;
}
k++;
}
while (line != null);
}
catch (Exception e)
{
e.printStackTrace()
}
return line;
}
}