2012-11-21 112 views
0

對不起,如果我的代碼看起來不好,我在編程方面沒有經驗。我需要從以下格式的.txt格式傳輸文本:日期 - 姓名 - 地址 - 等。將.txt讀取到二維數組中

我正在閱讀文件,然後使用String.split(「 - 」)分割字符串。我在循環中遇到問題。

try{ 
     File file = new File("testwrite.txt"); 
     Scanner scan = new Scanner(file); 
     String[] test = scan.nextLine().split("-"); 
     while(r<100){ 
      while(c<6){ 
       data[r][c] = test[c]; 
       test = scan.nextLine().split("-"); 
       c++; 
      } 
      r++; 
      c = 0 ; 
     } 
     System.out.println(data[1][5]); 
    }catch(Exception e){ 
     System.out.println("Error: " + e.getMessage()); 
    } 
+0

System.out.println(data [1] [5]) - 僅用於測試目的。 –

+0

看起來像'for'循環會更適合這個。 – arshajii

+0

首先第8行, test = scan.nextLine()。split(「 - 」); Test是一個字符串數組,你需要指定一個索引。 – Waleed

回答

2

二維數組就是「數組數組」,所以你可以直接使用split結果來存儲一行的數據。

  File file = new File("testwrite.txt"); 
      Scanner scanner = new Scanner(file); 
      final int maxLines = 100; 
      String[][] resultArray = new String[maxLines][]; 
      int linesCounter = 0; 
      while (scanner.hasNextLine() && linesCounter < maxLines) { 
       resultArray[linesCounter] = scanner.nextLine().split("-"); 
       linesCounter++; 
      } 
+0

這工作,非常感謝你的幫助! –

0

它看起來像你太頻繁地調用scan.nextLine()。每次調用scan.nextLine()時,它都會使掃描器前進到當前行。假設你的文件有100行,每行有6個「條目」(用「 - 」分隔),我會將test = scan.nextLine().split("-");移動到while循環的末尾(但仍在循環中),以便每行調用一次。

編輯...

建議的解決方案: 鑑於該格式的文件,

abcxyz

abcxyz ...(共100次)

使用此代碼:

try{ 
    File file = new File("testwrite.txt"); 
    Scanner scan = new Scanner(file); 
    String[] test = scan.nextLine().split("-"); 
    while(r<100){ 
     while(c<6){ 
      data[r][c] = test[c]; 
      c++; 
     } 
     r++; 
     c = 0 ; 
     test = scan.nextLine().split("-"); 
    } 
    System.out.println(data[1][5]); 
}catch(Exception e){ 
    System.out.println("Error: " + e.getMessage()); 
} 

然後使用data [line] [index]來訪問您的數據。從其它的字符,除了 -

BufferedReader reader = new BufferedReader(new FileReader(path)); 
int lineNum = 0; //Use this to skip past a column header, remove if you don't have one 
String readLine; 
while ((readLine = reader.readLine()) != null) { //read until end of stream 
    if (lineNum == 0) { 
     lineNum++; //increment our line number so we start with our content at line 1. 
     continue; 
    } 
    String[] nextLine = readLine.split("\t"); 

    for (int x = 0; x < nextLine.length; x++) { 
     nextLine[x] = nextLine[x].replace("\'", ""); //an example of using the line to do processing. 

     ...additional file processing logic here... 
    } 
} 

再次,在我的情況,我對標籤(\ t)的分裂,但你可以很容易地在拆分:

+0

這給出了「未找到線路」錯誤。 –

0

我拆標籤使用以下分隔的文件換行符。

根據The Javadoc for readline()A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

一旦你有你的線分裂了你的需要,只需要將它們分配給你的數組。