public void loadMetaData() throws IOException { pageFile.seek(offset); nextPageId = pageFile.readInt(); currentFill = pageFile.readInt(); bloomfilter = pageFile.readInt(); type = pageFile.readByte(); }
public static void loadAllOpenLevels(Player player, RandomAccessFile loadfile) throws IOException { System.out.printf("Entering map loader at %d!\n", loadfile.getFilePointer()); int mapsToLoad = loadfile.readInt(); for (int x = 0; x < mapsToLoad; x++) { System.out.printf("Loading a map at %d!\n", loadfile.getFilePointer()); int layer = loadfile.readInt(); System.out.printf("Looks like it's map %d!\n", layer); loadMap(layer, player, loadfile); } }
public int bubbleSort() throws Exception { boolean swapped = true; int j = 0; int counter = 0; while (swapped) { swapped = false; j++; for (int i = 0; i < length() - j; i++) { file.seek(i * 4); int one = file.readInt(); int two = file.readInt(); if (one > two) { file.seek(i * 4); file.writeInt(two); file.writeInt(one); swapped = true; counter++; } } } return counter; }
public void read() throws Exception { file.seek(0); System.out.print("[ "); while (file.getFilePointer() < file.length()) System.out.print(file.readInt() + " "); System.out.println("]"); }
private void loadDataXM(RandomAccessFile fp) throws IOException { byte[] b = new byte[20]; // WHY THE HELL AM I DOING THIS name = Util.readStringNoNul(fp, b, 20); System.out.printf("name: \"%s\"\n", name); fp.read(); // skip 0x1A byte // THIS CAN'T BE HAPPENING fp.read(b, 0, 20); // skip tracker name // OH HELL NO int xmver = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); System.out.printf("XM version: %04X\n", xmver); // WHAT IS THIS CRAP InhibitedFileBlock ifb = new InhibitedFileBlock(fp, Integer.reverseBytes(fp.readInt()) - 4); // HELP ME PLEASE int ordnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int respos = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // can't be bothered right now --GM int chnnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // yeah sure, allow out of range values if (chnnum > 64) throw new RuntimeException( String.format("%d-channel modules not supported (max 64)", chnnum)); int patnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int insnum = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmflags = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmspeed = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); int xmtempo = 0xFFFF & (int) Short.reverseBytes(ifb.readShort()); // OH PLEASE, STOP IT if (ordnum > 255) ordnum = 255; if (xmtempo > 255) xmtempo = 255; if (xmspeed > 255) xmspeed = 255; this.bpm = xmtempo; this.spd = xmspeed; this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_INSMODE | FLAG_STEREO | FLAG_VOL0MIX; if ((xmflags & 0x01) != 0) this.flags |= FLAG_LINEAR; // NONONONONONO System.out.printf("chn=%d ordnum=%d tempo=%d speed=%s\n", chnnum, ordnum, xmtempo, xmspeed); for (int i = 0; i < 256; i++) orderlist[i] = ifb.read(); for (int i = ordnum; i < 256; i++) orderlist[i] = 255; ifb.done(); // SAVE ME PLEEEEEAAASSSSEEEE for (int i = 0; i < patnum; i++) map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_XM, chnnum)); for (int i = 0; i < insnum; i++) map_ins.put((Integer) (i + 1), new SessionInstrument(fp, SessionInstrument.FORMAT_XM, this)); }
/* * gets an (uncompressed) stream representing the chunk data returns null if * the chunk is not found or an error occurs */ public synchronized DataInputStream getChunkDataInputStream(int x, int z) { if (outOfBounds(x, z)) { debugln("READ", x, z, "out of bounds"); return null; } try { int offset = getOffset(x, z); if (offset == 0) { // debugln("READ", x, z, "miss"); return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > sectorFree.size()) { debugln("READ", x, z, "invalid sector"); return null; } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { debugln("READ", x, z, "invalid length: " + length + " > 4096 * " + numSectors); return null; } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream( new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); DataInputStream ret = new DataInputStream( new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data)))); // debug("READ", x, z, " = found"); return ret; } debugln("READ", x, z, "unknown version " + version); return null; } catch (IOException e) { debugln("READ", x, z, "exception"); return null; } }
public static void main(String args[]) { try { String fname = "d:\\q.txt"; String mode; // mode = "r";//r : file must exist mode = "rw"; // rw : file will be created or opened // open the file RandomAccessFile raf = new RandomAccessFile(fname, mode); /* //seek and write demo raf.seek(10);//position file r/w pointer at index 10 wrt BOF //a seek beyond file size causes file to grow upto the seek value raf.write(65);//raf.write('A'); */ // r/w java datatypes int i1, i2; float f1, f2; char c1, c2; String s1, s2; i1 = -10; f1 = 1234.5678F; c1 = 'q'; s1 = "hello files"; raf.seek(0); // reach BOF raf.writeInt(i1); raf.writeFloat(f1); raf.writeChar(c1); raf.writeUTF(s1); raf.seek(0); // reach BOF i2 = raf.readInt(); f2 = raf.readFloat(); c2 = raf.readChar(); s2 = raf.readUTF(); System.out.println(i2); System.out.println(f2); System.out.println(c2); System.out.println(s2); // close the file raf.close(); } catch (IOException ex) { System.out.println(ex); // ex converts into ex.toString() } } // main
public static void main(String[] args) throws IOException { try ( // Create a random access file RandomAccessFile inout = new RandomAccessFile("inout.dat", "rw"); ) { // Clear the file to destroy the old contents if exists inout.setLength(0); // Write new integers to the file for (int i = 0; i < 200; i++) inout.writeInt(i); // Display the current length of the file System.out.println("Current file length is " + inout.length()); // Retrieve the first number inout.seek(0); // Move the file pointer to the beginning System.out.println("The first number is " + inout.readInt()); // Retrieve the second number inout.seek(1 * 4); // Move the file pointer to the second number System.out.println("The second number is " + inout.readInt()); // Retrieve the tenth number inout.seek(9 * 4); // Move the file pointer to the tenth number System.out.println("The tenth number is " + inout.readInt()); // Modify the eleventh number inout.writeInt(555); // Append a new number inout.seek(inout.length()); // Move the file pointer to the end inout.writeInt(999); // Display the new length System.out.println("The new length is " + inout.length()); // Retrieve the new eleventh number inout.seek(10 * 4); // Move the file pointer to the eleventh number System.out.println("The eleventh number is " + inout.readInt()); } }
public int dingPiao(String flightNum, String day, int seats) { int leftSeats = 0; try { long index = cacuIndex(day); long address = cacuAddr(flightNum); long absoluteAddress = index + address; raf.seek(absoluteAddress); int bookedSeats = raf.readInt(); String sqlString = "select seat,week from flight where flight='" + flightNum + "' "; ResultSet rs = sqlConnection.executeQuery(sqlString); int totalSeats = 0; String week = ""; while (rs.next()) { totalSeats = rs.getInt(1); week = rs.getString(2); } String c = isAbsence(day); int flag = 0; for (int i = 0; i < week.length(); i++) { String w = week.substring(i, i + 1); if (c.equals(w)) { flag = 1; break; } } if (flag == 1) { leftSeats = totalSeats - bookedSeats; if (leftSeats >= seats) { raf.seek(absoluteAddress); raf.writeInt(bookedSeats + seats); return -1; } else return leftSeats; } else return -2; } catch (Exception e) { e.printStackTrace(); } return leftSeats; }
/** * Get the next rtp packet recorded in the rtpdump file. * * @param loopFile if true, when the end of the rtpdump file is reached, this * <tt>RtpdumpFileReader</tt> will go back at the beginning of the file and get the first * packet. * @return a <tt>RawPacket</tt> containing all the information and data of the next rtp packet * recorded in the rtpdump file * @throws IOException if <tt>loopFile</tt> was false and the end of the file is reached. */ public RawPacket getNextPacket(boolean loopFile) throws IOException { if (loopFile && (stream.getFilePointer() >= stream.length())) { resetFile(); } byte[] rtpdumpPacket; int sizeInBytes; stream.readShort(); // read away an useless short (2 bytes) sizeInBytes = stream.readUnsignedShort(); rtpdumpPacket = new byte[sizeInBytes]; stream.readInt(); // read away the rtpdump timestamp stream.read(rtpdumpPacket); return new RawPacket(rtpdumpPacket, 0, rtpdumpPacket.length); }
public void tuiPiao(String flightNum, String day, int seats) { try { long index = cacuIndex(day); long address = cacuAddr(flightNum); long absoluteAddress = index + address; raf.seek(absoluteAddress); int bookedSeats = raf.readInt(); if (bookedSeats < seats) JOptionPane.showMessageDialog(null, "退票数大于已定票数!", "错误信息", JOptionPane.ERROR_MESSAGE); else { raf.seek(absoluteAddress); raf.writeInt(bookedSeats - seats); } } catch (Exception e) { } }
/** * Create a new DBWriter according to the input file name. * * @param fileName the name of the file * @exception FileNotFoundException from library call * @exception IOException from library call or if file is corrupted */ public DBWriter(String fileName) throws IOException { outStream = new RandomAccessFile(fileName, "rw"); lastPosition = outStream.length(); // case this is a new database if (lastPosition == 0) { wroteColumnNames = false; headerSize = 0; numRows = 0; CRC = 0; needReposition = false; } // case this might be an old database else if (lastPosition > MIN_DATA_OFFSET) { // check that we have a valid database here checkID(); wroteColumnNames = true; // read header data outStream.seek(HEAD_SIZE_OFFSET); headerSize = outStream.readLong(); numRows = outStream.readLong(); numColumns = outStream.readLong(); // read description outStream.seek(headerSize - DESCRIPTION_SIZE - ID_SIZE - CRC_SIZE); description = ""; for (int i = 0; i < DESCRIPTION_LENGTH; i++) description += outStream.readChar(); description = description.trim(); // read CRC outStream.seek(headerSize - CRC_SIZE); CRC = outStream.readInt(); // by default we append to an existing database needReposition = true; } // case this is not a database else throw new IOException("Attempting to load invalid database"); }
public boolean isFull(String flightNum, String day) { try { long index = cacuIndex(day); long address = cacuAddr(flightNum); long absoluteAddress = index + address; raf.seek(absoluteAddress); int bookedSeats = raf.readInt(); String sqlString = "select seat from flight where flight='" + flightNum + "'"; ResultSet rs = sqlConnection.executeQuery(sqlString); int totalSeats = 0; while (rs.next()) totalSeats = rs.getInt(1); if (totalSeats == bookedSeats) return true; else return false; } catch (Exception e) { return false; } }
public static void main(String args[]) { RandomAccessFile classe = null; Scanner entrada = new Scanner(System.in); Aluno b = new Aluno(); boolean achou = false; float media; try { classe = new RandomAccessFile("c:\\alunos.dat", "rw"); achou = false; while (true) { b.numero = classe.readInt(); b.nome = classe.readUTF(); b.curso = classe.readUTF(); b.nota1 = classe.readFloat(); b.nota2 = classe.readFloat(); media = (float) ((b.nota1 + b.nota2) / 2); if (media >= 7) { System.out.print("\nNome: " + b.nome); System.out.print("\nCurso: " + b.curso); System.out.print("\nNota1: " + b.nota1); System.out.print("\nNota2: " + b.nota2); System.out.print("\nMedia: " + media + "\n"); } } } // fim try catch (EOFException e) { try { classe.close(); } // fim try catch (IOException e2) { System.out.println("\nErro de I/O"); } } // fimn catch (EOFException e) catch (IOException e) { System.out.println("Erro na criacao o arquivo"); } } // fim main
public static String readArray(String s) { String output = "[ "; boolean endOfFile = false; try { RandomAccessFile input = new RandomAccessFile(s, "rw"); input.seek(0); while (!endOfFile) { try { output = output + input.readInt() + " "; } catch (EOFException e) { endOfFile = true; output = output + "]"; } } } catch (IOException e) { return e.getMessage(); } return output; }
private void loadDataIT(RandomAccessFile fp) throws IOException { byte[] b = new byte[26]; this.name = Util.readString(fp, b, 26); System.out.printf("name: \"%s\"\n", name); this.philigt = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int ordnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int insnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int smpnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int patnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); this.cwtv = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); this.cmwt = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); this.flags = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); this.special = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); this.gv = fp.read(); this.mv = fp.read(); this.spd = fp.read(); this.bpm = fp.read(); this.pwd = fp.read(); this.sep = fp.read(); int msglgth = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int msgoffs = Integer.reverseBytes(fp.readInt()); this.timestamp = Integer.reverseBytes(fp.readInt()); fp.read(chnpan, 0, 64); fp.read(chnvol, 0, 64); System.out.printf("ver: %04X / compat: %04X\n", cwtv, cmwt); // Load orderlist for (int i = 0; i < ordnum; i++) orderlist[i] = fp.readUnsignedByte(); for (int i = ordnum; i < 256; i++) orderlist[i] = 255; // Load pointers int[] insptrs = new int[insnum]; int[] smpptrs = new int[smpnum]; int[] patptrs = new int[patnum]; for (int i = 0; i < insnum; i++) insptrs[i] = Integer.reverseBytes(fp.readInt()); for (int i = 0; i < smpnum; i++) smpptrs[i] = Integer.reverseBytes(fp.readInt()); for (int i = 0; i < patnum; i++) patptrs[i] = Integer.reverseBytes(fp.readInt()); // TODO: read MIDI + timestamp bollocks // TODO: look up and/or reverse engineer said bollocks // Load data for (int i = 0; i < insnum; i++) { if (insptrs[i] != 0) { fp.seek(insptrs[i]); map_ins.put( (Integer) (i + 1), new SessionInstrument( fp, cmwt < 0x200 ? SessionInstrument.FORMAT_IT100 : SessionInstrument.FORMAT_IT200)); } } for (int i = 0; i < smpnum; i++) { if (smpptrs[i] != 0) { fp.seek(smpptrs[i]); map_smp.put((Integer) (i + 1), new SessionSample(fp, SessionSample.FORMAT_IT)); } } for (int i = 0; i < patnum; i++) { if (patptrs[i] != 0) { fp.seek(patptrs[i]); map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_IT)); } } }
private void loadDataMOD(RandomAccessFile fp) throws IOException { byte[] b = new byte[23]; this.name = Util.readStringNoNul(fp, b, 20); System.out.printf("name: \"%s\"\n", name); // check to see if we're a 15-sampler fp.seek(20 + 15 * 30 + 1); boolean poss_15smp = (fp.read() == (byte) 0x78); // get M.K. tag fp.seek(20 + 31 * 30 + 1 + 1 + 128); String mktag = Util.readStringNoNul(fp, b, 4); // set us up for reading interesting things int smpnum = 31; int chnnum = 4; boolean flt8 = false; // check mktag for gibberish for (int i = 0; i < 4; i++) { // System.out.printf("%d\n",b[i]); if (b[i] < 0x20 || b[i] > 0x7E) { if (!poss_15smp) throw new RuntimeException("not a 15-sample or 31-sample MOD"); System.out.println("15-sample module!"); smpnum = 15; mktag = "****"; break; } } if (mktag.equals("FLT8")) { flt8 = true; } else if (mktag.substring(1, 4).equals("CHN")) { // check values int cct = b[0] - '0'; if (cct >= 1 && cct <= 9) chnnum = cct; } else if (mktag.substring(2, 4).equals("CH") || mktag.substring(2, 4).equals("CN")) { // check values int cct1 = b[0] - '0'; int cct2 = b[1] - '0'; if (cct1 >= 0 && cct1 <= 9) if (cct2 >= 0 && cct2 <= 9) { int cct = cct1 * 10 + cct2; if (cct >= 1) chnnum = cct; } } // I forget what else is used. if (chnnum > 64) throw new RuntimeException( String.format("%d-channel modules not supported (max 64)", chnnum)); if (flt8) throw new RuntimeException("TODO: FLT8 loader"); // continue fp.seek(20); // load sample headers for (int i = 0; i < smpnum; i++) map_smp.put((Integer) (i + 1), new SessionSample(fp, SessionSample.FORMAT_MOD)); // load order count int ordnum = fp.read(); // ignore this next byte (well, at least for now) fp.read(); // load orderlist + calculate patnum int patnum = 0; for (int i = 0; i < 128; i++) { int v = orderlist[i] = fp.read(); if (v > patnum) patnum = v; } patnum++; // fix up orderlist for (int i = ordnum; i < 256; i++) orderlist[i] = 255; // skip M.K. tag if (smpnum == 31) fp.readInt(); // load patterns for (int i = 0; i < patnum; i++) map_pat.put((Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_MOD, chnnum)); // load sample data for (int i = 0; i < smpnum; i++) map_smp.get((Integer) (i + 1)).loadSampleDataMOD(fp); // set everything else! this.flags = FLAG_COMPATGXX | FLAG_OLDEFFECTS | FLAG_STEREO | FLAG_VOL0MIX; this.sep = 64; }
private void loadDataS3M(RandomAccessFile fp) throws IOException { byte[] b = new byte[28]; this.name = Util.readString(fp, b, 28); System.out.printf("name: \"%s\"\n", name); fp.readInt(); // first two bytes we've seen, second two are unused int ordnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int smpnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int patnum = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int s3flags = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int s3cwtv = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); int ffi = 0xFFFF & (int) Short.reverseBytes(fp.readShort()); fp.readInt(); // should have "SCRM" but really doesn't matter this.flags = FLAG_OLDEFFECTS | FLAG_VOL0MIX; this.gv = fp.read() * 2; this.spd = fp.read(); this.bpm = fp.read(); this.mv = fp.read(); fp.read(); // NO WE DON'T HAVE A GUS int dfpflag = fp.read(); // weird S3M crap // note: assuming default of 6/125 // it actually uses the previously-used speed/tempo if (this.spd == 0 || this.spd == 255) this.spd = 6; if (this.bpm < 33) this.bpm = 125; if ((this.mv & 0x80) != 0) { this.mv &= ~0x80; this.flags |= FLAG_STEREO; // XXX: this might need to be done internally in the player // if it turns out that IT does the same damn thing --GM this.mv = (this.mv * 11 + 4) >> 3; } // skip all that bollocks fp.seek(0x40); // load channel mappings // yes, we WILL want these! // though i don't think anyone's done anything completely bonkers // except Storlek and myself --GM int[] st3chnmap = new int[32]; for (int i = 32; i < 64; i++) { chnvol[i] = (byte) 0xC0; chnpan[i] = 0x20; } for (int i = 0; i < 32; i++) { chnpan[i] = 0; int v = fp.read(); st3chnmap[i] = v & 0x7F; // don't enable FM channels! chnvol[i] = ((v & 0x80) != 0 && (v & 0x7F) < 16) ? 0x40 : (byte) 0xC0; } // orderlist! // DON'T EVEN NEED TO FILTER IT YES :D for (int i = 0; i < ordnum; i++) orderlist[i] = fp.read(); for (int i = ordnum; i < 256; i++) orderlist[i] = 255; // load pointers int[] smpptrs = new int[smpnum]; int[] patptrs = new int[patnum]; for (int i = 0; i < smpnum; i++) smpptrs[i] = (0xFFFF & (int) Short.reverseBytes(fp.readShort())) * 16; for (int i = 0; i < patnum; i++) patptrs[i] = (0xFFFF & (int) Short.reverseBytes(fp.readShort())) * 16; // load default panning if necessary for (int i = 0; i < 32; i++) { int v = (dfpflag == 252) ? fp.read() : 0x10; int pan = (v & 0x10) != 0 ? (flags & FLAG_STEREO) != 0 ? (v & 0x08) != 0 ? 0xC : 0x3 : 0x7 : v & 15; // TODO: scale this crap correctly chnpan[i] = (byte) ((pan + 2) << 2); } // load data for (int i = 0; i < smpnum; i++) if (smpptrs[i] != 0) { fp.seek(smpptrs[i]); map_smp.put((Integer) (i + 1), new SessionSample(fp, SessionSample.FORMAT_S3M, ffi)); } for (int i = 0; i < patnum; i++) if (patptrs[i] != 0) { fp.seek(patptrs[i]); map_pat.put( (Integer) i, new SessionPattern(this, fp, SessionPattern.FORMAT_S3M, st3chnmap)); } // XXX: any other crap this needs? --GM }
public int readInt() throws IOException { return (raf.readInt()); }
public RegionFile(File path) { offsets = new int[SECTOR_INTS]; chunkTimestamps = new int[SECTOR_INTS]; fileName = path; debugln("REGION LOAD " + fileName); sizeDelta = 0; try { if (path.exists()) { lastModified = path.lastModified(); } file = new RandomAccessFile(path, "rw"); if (file.length() < SECTOR_BYTES) { /* we need to write the chunk offset table */ for (int i = 0; i < SECTOR_INTS; ++i) { file.writeInt(0); } // write another sector for the timestamp info for (int i = 0; i < SECTOR_INTS; ++i) { file.writeInt(0); } sizeDelta += SECTOR_BYTES * 2; } if ((file.length() & 0xfff) != 0) { /* the file size is not a multiple of 4KB, grow it */ for (int i = 0; i < (file.length() & 0xfff); ++i) { file.write((byte) 0); } } /* set up the available sector map */ int nSectors = (int) file.length() / SECTOR_BYTES; sectorFree = new ArrayList<Boolean>(nSectors); for (int i = 0; i < nSectors; ++i) { sectorFree.add(true); } sectorFree.set(0, false); // chunk offset table sectorFree.set(1, false); // for the last modified info file.seek(0); for (int i = 0; i < SECTOR_INTS; ++i) { int offset = file.readInt(); offsets[i] = offset; if (offset != 0 && (offset >> 8) + (offset & 0xFF) <= sectorFree.size()) { for (int sectorNum = 0; sectorNum < (offset & 0xFF); ++sectorNum) { sectorFree.set((offset >> 8) + sectorNum, false); } } } for (int i = 0; i < SECTOR_INTS; ++i) { int lastModValue = file.readInt(); chunkTimestamps[i] = lastModValue; } } catch (IOException e) { e.printStackTrace(); } }
/** Reads a MIDI track without doing anything to the data */ private void skipATrack(RandomAccessFile dos) throws IOException { if (VERBOSE) System.out.println("Skipping the tempo track . . ."); dos.readInt(); dos.skipBytes(dos.readInt()); }
/** * Repairs the chunk region file Returns -1 if the file had to be removed Returns -2 if we had no * access Returns -3 if file removal failed (from -1) Returns the amount of changed chunks * otherwise * * @param chunkfile * @param backupfolder * @return */ public static int repairRegion(File chunkfile, File backupfolder) { MyWorlds.log(Level.INFO, "Performing repairs on region file: " + chunkfile.getName()); RandomAccessFile raf = null; try { raf = new RandomAccessFile(chunkfile, "rw"); File backupfile = new File(backupfolder + File.separator + chunkfile.getName()); int[] locations = new int[1024]; for (int i = 0; i < 1024; i++) { locations[i] = raf.readInt(); } // Validate the data int editcount = 0; for (int i = 0; i < locations.length; i++) { int location = locations[i]; if (location == 0) continue; try { int offset = location >> 8; int size = location & 255; raf.seek((long) (offset * 4096)); int length = raf.readInt(); // Read and test the data if (length > 4096 * size) { editcount++; locations[i] = 0; MyWorlds.log(Level.WARNING, "Invalid length: " + length + " > 4096 * " + size); // Invalid length } else if (size > 0 && length > 0) { byte version = raf.readByte(); byte[] data = new byte[length - 1]; raf.read(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); // Try to load it all... DataInputStream stream; if (version == 1) { stream = new DataInputStream(new GZIPInputStream(bais)); } else if (version == 2) { stream = new DataInputStream(new InflaterInputStream(bais)); } else { stream = null; // Unknown version MyWorlds.log( Level.WARNING, "Unknown region version: " + version + " (we probably need an update here!)"); } if (stream != null) { // Validate the stream and close try { NBTBase base = NBTTagCompound.b((DataInput) stream); if (base == null) { editcount++; locations[i] = 0; MyWorlds.log(Level.WARNING, "Invalid tag compount at chunk " + i); } else if (!(base instanceof NBTTagCompound)) { editcount++; locations[i] = 0; MyWorlds.log(Level.WARNING, "Invalid tag compount at chunk " + i); } } catch (Exception ex) { // Invalid. editcount++; locations[i] = 0; MyWorlds.log(Level.WARNING, "Stream " + i); ex.printStackTrace(); } stream.close(); } } } catch (Exception ex) { editcount++; locations[i] = 0; ex.printStackTrace(); } } if (editcount > 0) { if (backupfolder.mkdirs() && copy(chunkfile, backupfile)) { // Write out the new locations raf.seek(0); for (int location : locations) { raf.writeInt(location); } } else { MyWorlds.log(Level.WARNING, "Failed to make a copy of the file, no changes are made."); return -2; } } // Done. raf.close(); return editcount; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (raf != null) raf.close(); } catch (Exception ex) { } try { chunkfile.delete(); return -1; } catch (Exception ex) { return -3; } }