static List<Answer> solve(int[] numbers) { int n = numbers.length; Element[] a = new Element[n]; for (int i = 0; i < n; i++) { a[i] = new Element(numbers[i], i); } int id = -1; for (int i = 0; i < n; i++) { if (luckies.contains(a[i].x)) { id = i; break; } } Element[] b = a.clone(); Arrays.sort(b); if (Arrays.equals(a, b)) { return new ArrayList<Answer>(); } if (id == -1) { return null; } boolean[] did = new boolean[n]; for (int i = 0; i < n; i++) { if (a[i] == b[i]) { did[i] = true; } } List<Answer> ans = new ArrayList<Answer>(); int cur = 0; while (cur < n) { while (b[id] != a[id]) { int newId = b[id].n; swap(id, b[id].n, ans, a); did[id] = true; id = newId; } while (cur < n && did[cur] || cur == id) { cur++; } if (cur < n) { int newId = cur; swap(cur, id, ans, a); id = newId; } } // for (int i = 1; i < n; i++) { // if (a[i].x < a[i - 1].x) { // throw new AssertionError(); // } // } // if (ans.size() > 2 * n) { // throw new AssertionError(); // } return ans; }
public DictionaryEntry lookup(byte utfBytes[], int hashCode, int charLength) { int res = Arrays.binarySearch(hashCodes, hashCode); if (res < 0) { return null; } DictionaryEntry entry = entries[res]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } int pos = res - 1; while ((pos >= 0) && (hashCodes[pos] == hashCode)) { entry = entries[pos]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } --pos; } pos = res + 1; while ((pos < entries.length) && (hashCodes[pos] == hashCode)) { entry = entries[pos]; if (Arrays.equals(entry.entryBytes, utfBytes)) { return entry; } ++pos; } return UNKNOWN; }
public static boolean objectsAreIdentical(Object o1, Object o2) { if (o1 == null && o2 == null) { return (true); } else if (o1 == null || o2 == null) { return (false); } if (o1.getClass() != o2.getClass()) { if ((o1 instanceof Map && o2 instanceof Map) || (o1 instanceof List && o2 instanceof List)) { // things actually OK } else { o1 = normaliseObject(o1); o2 = normaliseObject(o2); if (o1.getClass() != o2.getClass()) { Debug.out("Failed to normalise classes " + o1.getClass() + "/" + o2.getClass()); return (false); } } } if (o1 instanceof Long || o1 instanceof String) { return (o1.equals(o2)); } else if (o1 instanceof byte[]) { return (Arrays.equals((byte[]) o1, (byte[]) o2)); } else if (o1 instanceof List) { return (listsAreIdentical((List) o1, (List) o2)); } else if (o1 instanceof Map) { return (mapsAreIdentical((Map) o1, (Map) o2)); } else if (o1 instanceof Integer || o1 instanceof Boolean || o1 instanceof Float || o1 instanceof ByteBuffer) { return (o1.equals(o2)); } else { Debug.out("Invalid type: " + o1); return (false); } }
@Test public void ortest2() { final int[] arrayrr = new int[4000 + 4000 + 2]; int pos = 0; final MutableRoaringBitmap rr = new MutableRoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); arrayrr[pos++] = k; } rr.add(100000); rr.add(110000); final MutableRoaringBitmap rr2 = new MutableRoaringBitmap(); for (int k = 4000; k < 8000; ++k) { rr2.add(k); arrayrr[pos++] = k; } arrayrr[pos++] = 100000; arrayrr[pos++] = 110000; final MutableRoaringBitmap rror = MutableRoaringBitmap.or(rr, rr2); final int[] arrayor = rror.toArray(); Assert.assertTrue(Arrays.equals(arrayor, arrayrr)); }
/** * Determines if two Records are identical. This compares the name, type, class, and rdata (with * names canonicalized). The TTLs are not compared. * * @param arg The record to compare to * @return true if the records are equal, false otherwise. */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Record)) return false; Record r = (Record) arg; if (type != r.type || dclass != r.dclass || !name.equals(r.name)) return false; byte[] array1 = rdataToWireCanonical(); byte[] array2 = r.rdataToWireCanonical(); return Arrays.equals(array1, array2); }
private boolean notifyParameterListenersIfChanged( String parameter, byte[] newValue, byte[] oldValue) { if (oldValue == null || !Arrays.equals(newValue, oldValue)) { notifyParameterListeners(parameter); return true; } return false; }
public Message updateState(AuthenticationMessage msg) throws AuthenticationException, GeneralSecurityException { switch (state) { case CL_CHALLANGE_SENT: { ChallangeResponseMessage crm = null; byte[] resp; if (msg instanceof ChallangeResponseMessage) { crm = (ChallangeResponseMessage) msg; resp = crm.getResponse(); } else { throw new AuthenticationException("State Error"); } if (!Arrays.equals(randNumber, resp)) { throw new AuthenticationException("Authentication Failed"); } state = SR_AUTH_SERVER; // wait for challenge ChallangeCheckStatusMessage check = new ChallangeCheckStatusMessage(); check.setOk(true); return check; } case SR_AUTH_SERVER: { ChallangeMessage cm = null; if (msg instanceof ChallangeMessage) { cm = (ChallangeMessage) msg; } else { throw new AuthenticationException("State Error"); } // send reponse ChallangeResponseMessage crm = new ChallangeResponseMessage(); byte[] passhash = UserManager.v().getPassHash(username); if (passhash == null) { throw new AuthenticationException("User has no password"); } crm.produceResponse(cm.getChallange(), passhash); authenticated = true; logger.info("User " + username + " logged in"); state = DONE_STATE; // complete the challenege-response return crm; } default: { if (msg instanceof ChallangeCheckStatusMessage) { return null; } } } throw new AuthenticationException("State Incomplete"); }
public boolean equals(Object other) { Persistent1 otherPersistent1 = (Persistent1) other; if (int1 != otherPersistent1.int1) { System.out.println("int1 failed"); return false; } if (float1 != otherPersistent1.float1) { System.out.println("float1 failed"); return false; } if (long1 != otherPersistent1.long1) { System.out.println("long1 failed"); return false; } if (boolean1 != otherPersistent1.boolean1) { System.out.println("boolean1 failed"); return false; } if (string1 != otherPersistent1.string1 && (string1 != null && !string1.equals(otherPersistent1.string1) && otherPersistent1.string1 != null)) { System.out.println("string1 failed"); return false; } if (date1 != otherPersistent1.date1 && (date1 != null && !date1.equals(otherPersistent1.date1) && otherPersistent1.date1 != null)) { System.out.println("date1 failed"); return false; } if (bytes1 != otherPersistent1.bytes1 && (bytes1 != null && !Arrays.equals(bytes1, otherPersistent1.bytes1) && otherPersistent1.bytes1 != null)) { System.out.println("bytes1 failed"); return false; } if (codable1 != otherPersistent1.codable1 && (codable1 != null && !codable1.equals(otherPersistent1.codable1) && otherPersistent1.codable1 != null)) { System.out.println("codable1 failed"); return false; } return true; }
@Override public boolean equals(Object o) { boolean result = false; if (o != null && o.getClass() == getClass()) { Team oTeam = (Team) o; result = Arrays.equals(teammates, oTeam.teammates); } return result; }
public static void runTests() { try { // SHA1 sha1Jmule = new SHA1(); MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1"); SHA1 sha1Gudy = new SHA1(); // SHA1Az shaGudyResume = new SHA1Az(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); File dir = new File(dirname); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { FileChannel fc = new RandomAccessFile(files[i], "r").getChannel(); System.out.println("Testing " + files[i].getName() + " ..."); while (fc.position() < fc.size()) { fc.read(buffer); buffer.flip(); byte[] raw = new byte[buffer.limit()]; System.arraycopy(buffer.array(), 0, raw, 0, raw.length); sha1Gudy.update(buffer); sha1Gudy.saveState(); ByteBuffer bb = ByteBuffer.wrap(new byte[56081]); sha1Gudy.digest(bb); sha1Gudy.restoreState(); sha1Sun.update(raw); buffer.clear(); } byte[] sun = sha1Sun.digest(); sha1Sun.reset(); byte[] gudy = sha1Gudy.digest(); sha1Gudy.reset(); if (Arrays.equals(sun, gudy)) { System.out.println(" SHA1-Gudy: OK"); } else { System.out.println(" SHA1-Gudy: FAILED"); } buffer.clear(); fc.close(); System.out.println(); } } catch (Throwable e) { Debug.printStackTrace(e); } }
@Override public boolean equals(Object o) { boolean result = false; if (o != null && o.getClass() == getClass()) { Employee oEmp = (Employee) o; result = (id.equals(oEmp.id) && Arrays.equals(teams, oEmp.teams)); } return result; }
public void run() { try { InputStream in; OutputStream out; try { in = sk.getInputStream(); out = sk.getOutputStream(); } catch (IOException e) { throw (new RuntimeException(e)); } while (true) { try { int len = Utils.int32d(read(in, 4), 0); if (!auth && (len > 256)) return; Message msg = new MessageBuf(read(in, len)); String cmd = msg.string(); Object[] args = msg.list(); Object[] reply; if (auth) { Command cc = commands.get(cmd); if (cc != null) reply = cc.run(this, args); else reply = new Object[] {"nocmd"}; } else { if (cmd.equals("nonce")) { reply = new Object[] {nonce}; } else if (cmd.equals("auth")) { if (Arrays.equals((byte[]) args[0], ckey)) { reply = new Object[] {"ok"}; auth = true; } else { reply = new Object[] {"no"}; } } else { return; } } MessageBuf rb = new MessageBuf(); rb.addlist(reply); byte[] rbuf = new byte[4 + rb.size()]; Utils.uint32e(rb.size(), rbuf, 0); rb.fin(rbuf, 4); out.write(rbuf); } catch (IOException e) { return; } } } catch (InterruptedException e) { } finally { try { sk.close(); } catch (IOException e) { throw (new RuntimeException(e)); } } }
public boolean equals(Object oOther) { if ((oOther == null) || (!(oOther instanceof LINKID3V2Frame))) { return false; } LINKID3V2Frame oOtherLINK = (LINKID3V2Frame) oOther; return (Arrays.equals(m_abyFrameIdentifier, oOtherLINK.m_abyFrameIdentifier) && (((m_sURL == null) && (oOtherLINK.m_sURL == null)) || m_sURL.equals(oOtherLINK.m_sURL)) && m_sAdditionalData.equals(oOtherLINK.m_sAdditionalData)); }
// Class's override methods @Override public boolean equals(Object o) { /* Condition validation */ if (o == null) return false; /* Condition validation: Must be instance of FwiData or FwiMutableData */ if (!(o instanceof FwiData || o instanceof FwiMutableData)) { return false; } return Arrays.equals(this._bytes, ((FwiData) o)._bytes); }
public TestFile assertIsCopyOf(TestFile other) { assertIsFile(); other.assertIsFile(); assertEquals( String.format("%s is not the same length as %s", this, other), other.length(), this.length()); assertTrue( String.format("%s does not have the same content as %s", this, other), Arrays.equals(getHash("MD5"), other.getHash("MD5"))); return this; }
private void positionAtCentralDirectory64() throws IOException { this.skipBytes(4); this.archive.readFully(this.DWORD_BUF); this.archive.seek(ZipEightByteInteger.getLongValue(this.DWORD_BUF)); this.archive.readFully(this.WORD_BUF); if (!Arrays.equals(this.WORD_BUF, ZipOutputStream.ZIP64_EOCD_SIG)) { throw new ZipException("archive's ZIP64 end of central directory locator is corrupt."); } this.skipBytes(44); this.archive.readFully(this.DWORD_BUF); this.archive.seek(ZipEightByteInteger.getLongValue(this.DWORD_BUF)); }
static boolean divisibleBy8(String s, List<int[]> F, List<int[]> H) { int[] g = freq(s.toCharArray()); for (int[] f : F) { if (strictlyLess(f, g)) { return true; } } for (int[] h : H) { if (Arrays.equals(h, g)) { return true; } } return false; }
public static void main(String[] args) throws Exception { ByteArrayOutputStream bout; ByteArrayInputStream bin; ObjectOutputStream oout; ObjectInputStream oin; FileInputStream fin; File foof; CustomOutputStream cout; CustomInputStream cin; // test for backwards compatibility bout = new ByteArrayOutputStream(); foof = new File(System.getProperty("test.src", "."), "Foo.ser"); fin = new FileInputStream(foof); while (fin.available() > 0) bout.write(fin.read()); byte[] buf1 = bout.toByteArray(); bout = new ByteArrayOutputStream(); oout = new ObjectOutputStream(bout); Foo foo = new Foo(); oout.writeObject(foo); oout.flush(); byte[] buf2 = bout.toByteArray(); if (!Arrays.equals(buf1, buf2)) throw new Error("Incompatible stream format (write)"); fin = new FileInputStream(foof); oin = new ObjectInputStream(fin); Foo foocopy = (Foo) oin.readObject(); if (!foo.equals(foocopy)) throw new Error("Incompatible stream format (read)"); // make sure write hook not called when old protocol in use bout = new ByteArrayOutputStream(); cout = new CustomOutputStream(bout); cout.useProtocolVersion(PROTOCOL_VERSION_1); cout.writeObject(foo); if (cout.hookCalled) throw new Error("write descriptor hook should not be called"); // write custom class descriptor representations bout = new ByteArrayOutputStream(); cout = new CustomOutputStream(bout); cout.writeObject(foo); cout.flush(); bin = new ByteArrayInputStream(bout.toByteArray()); cin = new CustomInputStream(bin); foocopy = (Foo) cin.readObject(); if (!cout.hookCalled) throw new Error("write descriptor hook never called"); if (!cin.hookCalled) throw new Error("read descriptor hook never called"); if (!foo.equals(foocopy)) throw new Error("serialization failed when hooks active"); }
private void checkHashSet( SimulatedArchivalUnit sau, boolean namesOnly, boolean filter, byte[] expected) throws Exception { enableFilter(sau, filter); CachedUrlSet set = sau.getAuCachedUrlSet(); byte[] hash = getHash(set, namesOnly); assertEquals(expected, hash); String parent = sau.getUrlRoot() + "/branch1"; CachedUrlSetSpec spec = new RangeCachedUrlSetSpec(parent); set = sau.makeCachedUrlSet(spec); byte[] hash2 = getHash(set, namesOnly); assertFalse(Arrays.equals(hash, hash2)); }
@Test public void ortest() { final MutableRoaringBitmap rr = new MutableRoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr.add(k); } rr.add(100000); rr.add(110000); final MutableRoaringBitmap rr2 = new MutableRoaringBitmap(); for (int k = 0; k < 4000; ++k) { rr2.add(k); } final MutableRoaringBitmap rror = MutableRoaringBitmap.or(rr, rr2); final int[] array = rror.toArray(); final int[] arrayrr = rr.toArray(); Assert.assertTrue(Arrays.equals(array, arrayrr)); rr.or(rr2); final int[] arrayirr = rr.toArray(); Assert.assertTrue(Arrays.equals(array, arrayirr)); }
private int compare(Revision a, Revision b) { if (Arrays.equals(a._id, b._id)) return 0; Version va = getVersion(a); Version vb = getVersion(b); int n = va.compareTo(vb); if (n != 0) return n; if (a.created != b.created) return a.created > b.created ? 1 : -1; for (int i = 0; i < a._id.length; i++) if (a._id[i] != b._id[i]) return a._id[i] > b._id[i] ? 1 : -1; return 0; }
@Test public void andtest3() { final int[] arrayand = new int[11256]; int pos = 0; final MutableRoaringBitmap rr = new MutableRoaringBitmap(); for (int k = 4000; k < 4256; ++k) rr.add(k); for (int k = 65536; k < 65536 + 4000; ++k) rr.add(k); for (int k = 3 * 65536; k < 3 * 65536 + 1000; ++k) rr.add(k); for (int k = 3 * 65536 + 1000; k < 3 * 65536 + 7000; ++k) rr.add(k); for (int k = 3 * 65536 + 7000; k < 3 * 65536 + 9000; ++k) rr.add(k); for (int k = 4 * 65536; k < 4 * 65536 + 7000; ++k) rr.add(k); for (int k = 6 * 65536; k < 6 * 65536 + 10000; ++k) rr.add(k); for (int k = 8 * 65536; k < 8 * 65536 + 1000; ++k) rr.add(k); for (int k = 9 * 65536; k < 9 * 65536 + 30000; ++k) rr.add(k); final MutableRoaringBitmap rr2 = new MutableRoaringBitmap(); for (int k = 4000; k < 4256; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 65536; k < 65536 + 4000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 3 * 65536 + 1000; k < 3 * 65536 + 7000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 6 * 65536; k < 6 * 65536 + 1000; ++k) { rr2.add(k); arrayand[pos++] = k; } for (int k = 7 * 65536; k < 7 * 65536 + 1000; ++k) { rr2.add(k); } for (int k = 10 * 65536; k < 10 * 65536 + 5000; ++k) { rr2.add(k); } final MutableRoaringBitmap rrand = MutableRoaringBitmap.and(rr, rr2); final int[] arrayres = rrand.toArray(); for (int i = 0; i < arrayres.length; i++) if (arrayres[i] != arrayand[i]) System.out.println(arrayres[i]); Assert.assertTrue(Arrays.equals(arrayand, arrayres)); }
/** * Compares the contents of two streams by reading them. * * <p>NOTE: The streams get closed in any case. * * @param contents1 the first content stream * @param contents2 the second content stream * @return true iff both stream had the same length and the same data * @throws IOException if an I/O exception occurs while reading one of the streams */ public static boolean hasSameContents(InputStream contents1, InputStream contents2) throws IOException { try { int bufSize = 10000; byte[] buffer1 = new byte[bufSize]; byte[] buffer2 = new byte[bufSize]; boolean eof1 = false; boolean eof2 = false; while (!eof1 && !eof2) { int pos1 = 0; while (pos1 != bufSize) { int count = contents1.read(buffer1, pos1, bufSize - pos1); if (count == -1) { eof1 = true; break; } pos1 += count; } int pos2 = 0; while (pos2 != bufSize) { int count = contents2.read(buffer2, pos2, bufSize - pos2); if (count == -1) { eof2 = true; break; } pos2 += count; } if (eof1 || eof2) { if (pos1 != pos2 || !firstBytesEquals(buffer1, buffer2, pos1)) { return false; } } else { if (!Arrays.equals(buffer1, buffer2)) { return false; } } } return true; } finally { IOUtil.closeSilently(contents1); IOUtil.closeSilently(contents2); } }
public boolean equals(Object oOther) { if ((oOther == null) || (!(oOther instanceof COMRID3V2Frame))) { return false; } COMRID3V2Frame oOtherCOMR = (COMRID3V2Frame) oOther; return (m_oTextEncoding.equals(oOtherCOMR.m_oTextEncoding) && m_sPrice.equals(oOtherCOMR.m_sPrice) && m_sValidUntil.equals(oOtherCOMR.m_sValidUntil) && m_sContactUrl.equals(oOtherCOMR.m_sContactUrl) && (m_byReceivedAs == oOtherCOMR.m_byReceivedAs) && m_sNameOfSeller.equals(oOtherCOMR.m_sNameOfSeller) && m_sDescription.equals(oOtherCOMR.m_sDescription) && m_sPictureMimeType.equals(oOtherCOMR.m_sPictureMimeType) && Arrays.equals(m_abySellerLogoData, oOtherCOMR.m_abySellerLogoData)); }
@Override @Nullable public StoredBlock get(Sha256Hash hash) throws BlockStoreException { final MappedByteBuffer buffer = this.buffer; if (buffer == null) throw new BlockStoreException("Store closed"); lock.lock(); try { StoredBlock cacheHit = blockCache.get(hash); if (cacheHit != null) return cacheHit; if (notFoundCache.get(hash) != null) return null; // Starting from the current tip of the ring work backwards until we have either found the // block or // wrapped around. int cursor = getRingCursor(buffer); final int startingPoint = cursor; final int fileSize = getFileSize(); final byte[] targetHashBytes = hash.getBytes(); byte[] scratch = new byte[32]; do { cursor -= RECORD_SIZE; if (cursor < FILE_PROLOGUE_BYTES) { // We hit the start, so wrap around. cursor = fileSize - RECORD_SIZE; } // Cursor is now at the start of the next record to check, so read the hash and compare it. buffer.position(cursor); buffer.get(scratch); if (Arrays.equals(scratch, targetHashBytes)) { // Found the target. StoredBlock storedBlock = StoredBlock.deserializeCompact(params, buffer); blockCache.put(hash, storedBlock); return storedBlock; } } while (cursor != startingPoint); // Not found. notFoundCache.put(hash, notFoundMarker); return null; } catch (ProtocolException e) { throw new RuntimeException(e); // Cannot happen. } finally { lock.unlock(); } }
private void positionAtCentralDirectory() throws IOException { this.positionAtEndOfCentralDirectoryRecord(); boolean found = false; final boolean searchedForZip64EOCD = this.archive.getFilePointer() > 20L; if (searchedForZip64EOCD) { this.archive.seek(this.archive.getFilePointer() - 20L); this.archive.readFully(this.WORD_BUF); found = Arrays.equals(ZipOutputStream.ZIP64_EOCD_LOC_SIG, this.WORD_BUF); } if (!found) { if (searchedForZip64EOCD) { this.skipBytes(16); } this.positionAtCentralDirectory32(); } else { this.positionAtCentralDirectory64(); } }
/** * Does the actual work for decrypting - if version does not match current cipher then tries the * previous cipher */ private Message decryptMessage(Cipher cipher, Message msg) throws Exception { EncryptHeader hdr = (EncryptHeader) msg.getHeader(this.id); if (!Arrays.equals(hdr.getVersion(), getSymVersion())) { log.warn( "attempting to use stored cipher as message does not use current encryption version "); cipher = keyMap.get(new AsciiString(hdr.getVersion())); if (cipher == null) { log.warn("unable to find a matching cipher in previous key map"); return null; } log.trace("decrypting using previous cipher version"); synchronized (cipher) { return _decrypt(cipher, msg, hdr.encryptEntireMessage()); } } return _decrypt(cipher, msg, hdr.encryptEntireMessage()); }
protected void checkError(ErrorQueue equeue, ANTLRMessage expectedMessage) throws Exception { // System.out.println("errors="+equeue); ANTLRMessage foundMsg = null; for (int i = 0; i < equeue.errors.size(); i++) { ANTLRMessage m = (ANTLRMessage) equeue.errors.get(i); if (m.errorType == expectedMessage.errorType) { foundMsg = m; } } assertTrue("no error; " + expectedMessage.errorType + " expected", equeue.errors.size() > 0); assertTrue("too many errors; " + equeue.errors, equeue.errors.size() <= 1); assertNotNull("couldn't find expected error: " + expectedMessage.errorType, foundMsg); /* assertTrue("error is not a GrammarSemanticsMessage", foundMsg instanceof GrammarSemanticsMessage); */ assertTrue(Arrays.equals(expectedMessage.args, foundMsg.args)); }
/** * Semantics is similar to {@link org.openide.windows.TopComponent#getActivatedNodes()} except * that this method returns File objects instead od Nodes. Every node is examined for Files it * represents. File and Folder nodes represent their underlying files or folders. Project nodes * are represented by their source groups. Other logical nodes must provide FileObjects in their * Lookup. * * @return File [] array of activated files * @param nodes or null (then taken from windowsystem, it may be wrong on editor tabs #66700). */ public static Context getCurrentContext(Node[] nodes) { if (nodes == null) { nodes = TopComponent.getRegistry().getActivatedNodes(); } if (Arrays.equals(contextNodesCached.get(), nodes)) { Context ctx = contextCached.get(); if (ctx != null) return ctx; } VCSContext vcsCtx = VCSContext.forNodes(nodes); Context ctx = new Context( new HashSet(vcsCtx.computeFiles(cvsFileFilter)), new HashSet(vcsCtx.getRootFiles()), new HashSet(vcsCtx.getExclusions())); contextCached = new WeakReference<Context>(ctx); contextNodesCached = new WeakReference<Node[]>(nodes); return ctx; }
static void testCopyInputStreamToFile(int size) throws IOException { Path tmpdir = createTempDirectory("blah"); Path source = tmpdir.resolve("source"); Path target = tmpdir.resolve("target"); try { boolean testReplaceExisting = rand.nextBoolean(); // create source file byte[] b = new byte[size]; rand.nextBytes(b); write(source, b); // target file might already exist if (testReplaceExisting && rand.nextBoolean()) { write(target, new byte[rand.nextInt(512)]); } // copy from stream to file InputStream in = new FileInputStream(source.toFile()); try { long n; if (testReplaceExisting) { n = copy(in, target, StandardCopyOption.REPLACE_EXISTING); } else { n = copy(in, target); } assertTrue(in.read() == -1); // EOF assertTrue(n == size); assertTrue(size(target) == size); } finally { in.close(); } // check file byte[] read = readAllBytes(target); assertTrue(Arrays.equals(read, b)); } finally { deleteIfExists(source); deleteIfExists(target); delete(tmpdir); } }