2016-03-02 73 views
1

如何从Java文件中的文件中获取短数组(16位)?要将文件简写为[]

这是我的尝试:

final static String FILE_NAME_INPUT = "./example.txt"; 

public static void main(String[] args) { 
    readFile(FILE_NAME_INPUT); 
} 

public static void readFile(String filename) { 
    short[] buffer = null; 
    File a_file = new File(filename); 
    try { 
     File file = new File(filename); 

     FileInputStream fis = new FileInputStream(filename); 
     DataInputStream dis = new DataInputStream(fis); 

     int length = (int)a_file.length(); 
     buffer = new short[length]; 

     //dis.readShort(buffer); DOESN'T WORK 

     for(int i = 0; i < length; i++) { 
      System.out.println("buffer[" + i + "]: " + buffer[i]); 
     } 

     dis.close(); 
    } 
    catch(FileNotFoundException fe) { 
     System.out.println("FileNotFoundException: " + fe); 
    } 
    catch(IOException ioe) { 
     System.out.println("IOException: " + ioe); 
    } 
} 

但线dis.readShort(buffer)不起作用,因为readShort()必须没有参数。

感谢

回答

0

你的缓存数组是空的,但如果你想检查DataInputStream你可以使用类似的东西

int counter =0; 
    while(dis.available()>0) 
      { 
       // read two bytes from data input 

       short s = dis.readShort(); 

       // print the short value 
       buffer[counter] = s; 
       System.out.print(s+" "); 
       counter++; 
     } 
+0

感谢您的答复。好吧,但我想要一个文件中所有短小的列表(数组),而不仅仅是一个。所以我想用表示该文件的短裤填充缓冲区数组。 – lon

+0

所以你想把文本文件中的所有值放到一个数组中或者我误解了 – imoteb

+0

是的,我想要那个。 – lon