我試着讓我的Android應用程序從一個文本文件的讀取和隨機選擇一個條目,然後顯示它,我怎麼會去這樣做?我想我必須使用緩衝區讀取器或輸入流命令,但我不知道如何使用這些,我嘗試了谷歌搜索,但沒有找到很多的幫助。從文件中讀取並顯示隨機線
據我所知(並與一些幫助)我要讀的文本文件,將其添加到字符串?並使用以下命令隨機選擇一個條目
Random.nextInt(String[].length-1).
我該如何去做這件事? :\ IM很新的這一切bufferreader東西等
我試着讓我的Android應用程序從一個文本文件的讀取和隨機選擇一個條目,然後顯示它,我怎麼會去這樣做?我想我必須使用緩衝區讀取器或輸入流命令,但我不知道如何使用這些,我嘗試了谷歌搜索,但沒有找到很多的幫助。從文件中讀取並顯示隨機線
據我所知(並與一些幫助)我要讀的文本文件,將其添加到字符串?並使用以下命令隨機選擇一個條目
Random.nextInt(String[].length-1).
我該如何去做這件事? :\ IM很新的這一切bufferreader東西等
下面是從文本文件閱讀一些簡單的代碼。你需要修改它以在線路上分割,顯然它還是很好的解決TODO問題,但它應該讓你開始。
try
{
InputStream is = new FileInputStream(m_file);
if(m_is == null)
{
openInputStream();
}
StringBuilder sb = new StringBuilder();
//TODO: get a buffered stream going, it should be more efficient
byte[] buf = new byte[100];
int readLen;
while((readLen = is.read(buf, 0, 100)) != -1)
{
sb.append(new String(buf, 0, readLen));
}
closeInputStream();
return sb.toString();
}
catch (FileNotFoundException e)
{
//TODO: handle this
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
}
}
您在這裏詢問2個不同的操作。不要把它們混淆在一起,把問題弄混淆。你想知道如何:
隨機選擇從一組串1串。
// Read in the file into a list of strings
BufferedReader reader = new BufferedReader(new FileReader("inputfile.txt"));
List<String> lines = new ArrayList<String>();
String line = reader.readLine();
while(line != null) {
lines.add(line);
line = reader.readLine();
}
// Choose a random one from the list
Random r = new Random();
String randomString = lines.get(r.nextInt(lines.size()));
順便說一句,我已經忽略了所有的嘗試/捕獲清晰。 – wolfcastle
/*This sample code shows how to read one term and its definition from
the file using TextIO.
The code just reads the term and the definition in to a String.
To read the whole file the simplest solution is to have an array
of String for the terms and an array of String for the definitions
and to ensure that you store the definition for a term at the same
index position in the definitions array as you store the term it
defines in the term array.
If you find that the TextIO window is too narrow to display the whole
of some of the lines of the definition on one line you can edit the text
file sothat each line contains fewer words (this may depend on your
screen resolution).
*/
public class Read from a txt file {
public static void main(String[]args){
String term = "";
String definition = "";
TextIO.readFile("Your_file.txt");
TextIO.putln("Just read this term from file: " + term);
String str;
do {
str = TextIO.getln();
definition = definition + str + "\n";
} while (str.length() != 0);
TextIO.putln(definition);
// Once you have read all the file take input from keyboard:
TextIO.readStandardInput();
}
}
確定「從一個txt文件中讀取」是一個有效的類名(含空格)。我沒有改變它,因爲我不想改變你從TXT文件閱讀代碼 – Paras
是definitly無效的類名;) –
啊,可惜的是Android不支持[*'java.nio.file.Files.readAllLines' *](http://www.kodejava.org/examples /813.html)! – Adam