gpt4 book ai didi

android - 读取文件中的上一行

转载 作者:行者123 更新时间:2023-11-30 03:51:59 26 4
gpt4 key购买 nike

我在下面有这段代码,它读取下一行直到未编号文件的末尾(文件中的行没有编号)并且它工作得很好。现在,我想读取前几行(向后读取)。如果也可能,随机播放(读取随机行)。任何想法。

这是一个例子:

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

}

最佳答案

您可以使用我的库 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;
}
}

关于android - 读取文件中的上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com