2013-07-17 55 views
1

如何順序讀取文件?如何更改此主要方法以順序讀取文件

public static void main(String[] args){ 
    String fichier ="E:\\fichiers\\test.txt"; 

    int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139}; 
    String tabS[] = new String[14]; 


    for(int i=0; i<tab.length; i++){ 

     char cbuf[] = new char[tab[i]]; 

     try { 

      InputStream  ips = new FileInputStream(fichier); 
      InputStreamReader ipsr = new InputStreamReader(ips); 
      BufferedReader br = new BufferedReader(ipsr); 

      br.read(cbuf, 0, tab[i]); 

      tabS[i] = new String(cbuf); 
      System.out.println(tabS[i]); 

     } catch (Exception e){ 
      System.out.println(e.toString()); 
     } 
    } 
} 

我的文件內容只有一行:

BOUUUUUUUUUUUUUUUUUUUUUU! 

當我運行自述方法,我得到這個:

BO 
BO 
BOUUUUUUUUUUUUUUUUUU 
BOUUUUUU 
BOUUUUUUUUUUUUUUUUUU 
BOUUUUUU 
BOUU 
BOU 
BOUUUUU 
BOU 
BOU 
BOU 
BOUUUUUUUUUUUUUUUU 
BOUUUUUUUUUUUUUUUUUUUUUU! 

這裏的問題是,每次他開始閱讀文件,它開始位置0.

任何幫助嗎?

+0

完全不清楚你在這裏試圖實現的目標......但是這個代碼以多種方式被打破。 –

+0

看起來你正在做的是程序正在做的事情:每次通過循環時,打開文件(從文件開始處開始),讀取一些字符並打印出來。你希望達到什麼目的? – Steve

回答

2

它看起來像我只是需要在流創建後移動try/catch中的for循環。

public static void main(String[] args){ 
    String fichier ="E:\\fichiers\\test.txt"; 

    int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139}; 
    String tabS[] = new String[14]; 

    try { 

     InputStream  ips = new FileInputStream(fichier); 
     InputStreamReader ipsr = new InputStreamReader(ips); 
     BufferedReader br = new BufferedReader(ipsr); 

     for(int i=0; i<tab.length; i++){ 

      char cbuf[] = new char[tab[i]]; 

      br.read(cbuf, 0, tab[i]); 

      tabS[i] = new String(cbuf); 
      System.out.println(tabS[i]); 
     } 

    } catch (Exception e){ 
     System.out.println(e.toString()); 
    } 
} 
2

看你有:

int tab[] = {2, 2, 20, 8, 20, 8, 4, 3, 7, 3, 3, 3, 18, 139}; 

你的輸出是:

BO      // length 2 
BO      // length 2 
BOUUUUUUUUUUUUUUUUUU  // length 20 
BOUUUUUU     // length 8 
BOUUUUUUUUUUUUUUUUUU 
BOUUUUUU 
BOUU 
BOU 
BOUUUUU 
BOU 
BOU 
BOU 
BOUUUUUUUUUUUUUUUU 
BOUUUUUUUUUUUUUUUUUUUUUU! 

這使得給定的意義:

 br.read(cbuf, 0, tab[i]); 
     tabS[i] = new String(cbuf); 
     System.out.println(tabS[i]); 

它在每次迭代中,因爲開始在位置0你有:

 InputStream  ips = new FileInputStream(fichier); 
     InputStreamReader ipsr = new InputStreamReader(ips); 
     BufferedReader br = new BufferedReader(ipsr); 

裏面的for循環。只需將其從循環中移除以糾正這種情況:

try 
{ 
     InputStream  ips = new FileInputStream(fichier); 
     InputStreamReader ipsr = new InputStreamReader(ips); 
     BufferedReader br = new BufferedReader(ipsr); 

     for(int i=0; i<tab.length; i++) 
     { 
      char cbuf[] = new char[tab[i]]; 
      br.read(cbuf, 0, tab[i]); 
      tabS[i] = new String(cbuf); 

      System.out.println(tabS[i]); 
     } 

} 
catch (Exception e) 
{ 
    System.out.println(e.toString()); 
}