簡體   English   中英

InputStreamReader並從.txt文件讀取隨機行

[英]InputStreamReader and reading random lines from .txt file

我的應用程序有一種方法可以從文本文件中讀取隨機行並將其返回。 我使用randTxt()從txt文件讀取並返回隨機行。 但每次只顯示同一行(第一行)。

public String randTxt(){

  // Read in the file into a list of strings
  InputStreamReader inputStream = new InputStreamReader(getResources().openRawResource(R.raw.randomstuff));
  //ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

  String theLine="";
  int i;
  try {
    i = inputStream.read();
    while (i != -1) {
      i = inputStream.read();
    }
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  LineNumberReader  rdr = new LineNumberReader(inputStream);
  int numLines = 30;
  Random r = new Random();
  rdr.setLineNumber(r.nextInt(numLines));

  try {
    theLine = rdr.readLine();
  } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }

  return theLine;
}

我該如何解決? 有人可以解釋我的代碼有什么問題嗎?

這是使用BufferedReader進行所需操作的框架。 在這種情況下,您不需要將值存儲在臨時數組中。

InputStreamReader inputStream = new InputStreamReader
  (getResources().openRawResource(R.raw.randomstuff));
BufferedReader br = new BufferedReader(inputStream);
int numLines = 30;
Random r = new Random();
int desiredLine = r.nextInt(numLines);

String theLine="";
int lineCtr = 0;
while ((theLine = br.readLine()) != null)   {
  if (lineCtr == desiredLine) {
    break;
  }
  lineCtr++;
 }
...
Log.d(TAG, "Magic line is: " +theLine);

您已獲得有關如何修復代碼的答案,但沒有解釋為什么我們的原始代碼無法正常工作。

LineNumberReader.setLineNumber(int)不會移到實際行,它只是更改您呼叫當前行的號碼。

因此,假設您讀了兩行, getLineNumber()現在將返回2(它從0開始,每次遇到換行符時增加1)。 如果現在使用setLineNumber(10) ,則getLineNumber()將返回10。讀取另一行(第三行)將導致getLineNumber()返回11。

Java Doc中對此進行了描述。

inputStream.read不返回行號。 它返回已讀取的字節。 這不是您逐行閱讀的方式。 要逐行讀取,應使用緩沖讀取器的readLine方法。 此時將所有內容讀入本地數組並使用該數組隨機獲取條目(而不是使用行號讀取器)可能更容易。

public String getRandomLine(String fileLoc) throws IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(fileLoc));
    ArrayList<String> lines = new ArrayList<String>();

    String line =null;
    while( (line = reader.readLine())!= null ) 
        lines.add(line);

    // Choose a random one from the list
    return lines.get(new Random().nextInt(lines.size()));
}
public String getRandomLineOpt(String fileLoc)throws IOException
{
    File f=new File(fileLoc);
    RandomAccessFile rcf=new RandomAccessFile(f, "r");
    long rand = (long)(new Random().nextDouble()*f.length());
    rcf.seek(rand);
    rcf.readLine();
    return rcf.readLine();
}

我認為Random()函數返回的值介於0和1之間。因此,您可能必須將其乘以100才能獲得整數值。 甚至可以考慮對您確保最終獲得的索引介於0和上限之間的MOD“您的上限”操作

在setLineNumber()方法中使用由此計算出的索引。

編輯:正如約翰所說,我們可以使用Random()對象獲取整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM