2013-01-04 31 views
0

訪問字符串我有以下內容的文本文件:如何通過文件位置的Java

one 
two 
three 
four 

我想訪問字符串「三國」以其在Java.I文本文件中的位置在谷歌上找到了子串的概念,但無法使用它。

到目前爲止,我能夠讀取該文件的內容:

import java.io.*; 
class FileRead 
{ 
public static void main(String args[]) 
    { 
    try{ 
    // Open the file that is the first 
    // command line parameter 
    FileInputStream fstream = new FileInputStream("textfile.txt"); 
    // Get the object of DataInputStream 
    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String strLine; 
    //Read File Line By Line 
    while ((strLine = br.readLine()) != null) { 
    // Print the content on the console 
    System.out.println (strLine); 
    } 
    //Close the input stream 
    in.close(); 
    }catch (Exception e){//Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
    } 
    } 

}

我想申請的子概念到file.It要求的位置並顯示出字符串。

String Str = new String("Welcome to Tutorialspoint.com"); 
System.out.println(Str.substring(10, 15)); 
+2

格式化您的代碼。 – Shivam

+0

請不要用Reader包裝DataInputStream。您不需要DataInputStream,因此將其刪除。 http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html#!/2012/08/java-memes-which-refuse-to-die.html –

+0

你的問題是什麼? –

回答

0

在文本文件中查找\r\n(換行符)。這樣你應該可以計算包含你的字符串的行。

你在現實中的文件是這樣

one\r\n 
two\r\n 
three\r\n 
four\r\n 
+0

am able做到這一點。但我想訪問讓我們通過其2個位置的開始和結束位置說出文件中的刺「三」。我不直接搜索字符串。 – Deathstar

+0

所以你的位置是row和lineStartIndex和lineEndIndex? – sschrass

+0

更好:start = row + lineStartIndex和end = row + lineEndIndex。注意它不會變成負面! – sschrass

2

如果你知道字節的文件中偏移,你有興趣,然後是簡單的:

RandomAccessFile raFile = new RandomAccessFile("textfile.txt", "r"); 
raFile.seek(startOffset); 
byte[] bytes = new byte[length]; 
raFile.readFully(bytes); 
raFile.close(); 
String str = new String(bytes, "Windows-1252"); // or whatever encoding 

但這個工作您必須使用字節偏移量,而不是字符偏移量 - 如果文件使用可變寬度編碼(例如UTF-8)進行編碼,則無法直接查找第n個字符,你必須從文件頂部開始讀取並丟棄前n-1個字符。

+0

或者只是使用'InputStream.skip(numberOfBytes)' – JayC667

+1

@ JayC667並仔細檢查返回值以確保它確實跳過了您要求的字節數 - 跳過允許跳過少於'numberOfBytes'。 –

0

您好像在尋找this。我在那裏發佈的代碼在字節級別工作,所以它可能不適合你。另一個選擇是使用BufferedReader並且只讀取像這樣的循環中的單個字符:

String getString(String fileName, int start, int end) throws IOException { 
    int len = end - start; 
    if (len <= 0) { 
     throw new IllegalArgumentException("Length of string to output is zero or negative."); 
    } 

    char[] buffer = new char[len]; 
    BufferedReader reader = new BufferedReader(new FileReader(fileName)); 
    for (int i = 0; i < start; i++) { 
     reader.read(); // Ignore the result 
    } 

    reader.read(buffer, 0, len); 
    return new String(buffer); 
} 
相關問題