- Public static void ReadFile (String fileName) {
- File File = new file (FileName);
- if (file.exists ()) {
- try {
- FileInputStream in = new FileInputStream (file);
- DataInputStream dis=New DataInputStream (in);
- byte[] itembuf = new byte[20];
- //Market code
- Dis.read (Itembuf, 0, 8);
- String Marketid =new String (Itembuf,0,8);
- //Market name
- Dis.read (Itembuf, 0, ); After the Read method reads a certain length, the data being read is removed from the stream, so the next read still starts at 0
- String marketname =new String (Itembuf,0,20);
- //Previous trading day date
- Dis.read (Itembuf, 0, 8);
- String lasttradingday = new String (Itembuf,0,8);
- //Current trading day Date
- Dis.read (Itembuf, 0, 8);
- String curtradingday = new String (Itembuf,0,8);
- //Trading status
- Dis.read (Itembuf, 0, 1);
- String marketstatus = new String (Itembuf,0,1);
- //Number of trading hours
- Short tradeperiodnum = Dis.readshort ();
- System.out.println ("Market code:" + Marketid);
- System.out.println ("Market Name:" + marketname);
- System.out.println ("Last trading day Date:" + Lasttradingday);
- System.out.println ("date of the current trading day:" + curtradingday);
- System.out.println ("date of the current trading day:" + curtradingday);
- SYSTEM.OUT.PRINTLN ("Trading Status:" + Marketstatus);
- System.out.println ("Number of trading Hours:" + tradeperiodnum);
- } catch (IOException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }finally{
- //close
- }
- }
- }
/** * 随机读取文件内容 */ public static void readFileByRandomAccess(String fileName) { RandomAccessFile randomFile = null; try { System.out.println("随机读取一段文件内容:"); // 打开一个随机访问文件流,按只读方式 randomFile = new RandomAccessFile(fileName, "r"); // 文件长度,字节数 long fileLength = randomFile.length(); // 读文件的起始位置 int beginIndex = (fileLength > 4) ? 4 : 0; // 将读文件的开始位置移到beginIndex位置。 randomFile.seek(beginIndex); byte[] bytes = new byte[10]; int byteread = 0; // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。 // 将一次读取的字节数赋给byteread while ((byteread = randomFile.read(bytes)) != -1) { System.out.write(bytes, 0, byteread); } } catch (IOException e) { e.printStackTrace(); } finally { if (randomFile != null) { try { randomFile.close(); } catch (IOException e1) { } } } }
How Java reads binary files