List of usage examples for java.nio.file Files readAllBytes
public static byte[] readAllBytes(Path path) throws IOException
From source file:com.exalttech.trex.util.PacketUtil.java
/** * Read file as String//from w w w. ja v a2 s . com * * @param fileName * @return * @throws IOException * @throws URISyntaxException */ public String getFileContent(String fileName) throws IOException, URISyntaxException { return new String(Files.readAllBytes(Paths.get(getClass().getResource("/files/" + fileName).toURI()))); }
From source file:com.seleritycorp.common.base.http.client.FileHttpClient.java
@Override protected CloseableHttpResponse doExecute(HttpHost target, HttpRequest request, HttpContext context) throws IOException, ClientProtocolException { final StatusLine statusLine; final FileHttpClientResponse response; byte[] content = null; String uri = request.getRequestLine().getUri(); if (uri.startsWith("file://")) { File file = new File(URI.create(uri)); uri = file.getAbsolutePath();//www . j a v a 2s . c om } Path path = Paths.get(uri); if (request instanceof HttpGet) { if (Files.exists(path)) { if (Files.isReadable(path)) { if (!Files.isDirectory(path)) { content = Files.readAllBytes(path); statusLine = createStatusLine(HttpStatus.SC_OK, "OK"); } else { // Trying to GET a directory statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request"); } } else { // User does not have sufficient privilege to access the file statusLine = createStatusLine(HttpStatus.SC_FORBIDDEN, "Forbidden"); } } else { // File does not exist. statusLine = createStatusLine(HttpStatus.SC_NOT_FOUND, "Not Found"); } } else { // Request is not a HttpGet request. We currently only support GET, so we flag that the // client sent an illegal request. statusLine = createStatusLine(HttpStatus.SC_BAD_REQUEST, "Bad Request"); } response = new FileHttpClientResponse(statusLine); if (content != null) { response.setEntity(new ByteArrayEntity(content)); } return response; }
From source file:net.sourceforge.cobertura.test.ParentChildStaticFieldTest.java
@Test public void parentChildStaticFieldShouldWorkAfterInstrumentalizationTest() throws Exception { /*/* w w w .jav a2s . c o m*/ * Use a temporary directory and create a few sources files. */ File tempDir = TestUtils.getTempDir(); File srcDir = new File(tempDir, "src"); File instrumentDir = new File(tempDir, "instrument"); File mainSourceFile = new File(srcDir, "mypackage/ParentChildStaticField.java"); File datafile = new File(srcDir, "cobertura.ser"); mainSourceFile.getParentFile().mkdirs(); byte[] encoded = Files.readAllBytes(Paths.get( "src/test/resources/examples/basic/src/com/example/simple/ParentChildStaticFieldExample.java")); FileUtils.write(mainSourceFile, new String(encoded, "utf8")); TestUtils.compileSource(ant, srcDir); TestUtils.instrumentClasses(ant, srcDir, datafile, instrumentDir); //moving instrumented classes so we don't have to change classpaths FileUtils.copyDirectory(instrumentDir, srcDir); /* * Kick off the Main (instrumented) class. */ Java java = new Java(); java.setProject(TestUtils.project); java.setClassname("mypackage.ParentChildStaticField"); java.setDir(srcDir); java.setFork(true); java.setFailonerror(true); java.setClasspath(TestUtils.getCoberturaDefaultClasspath()); java.execute(); }
From source file:io.druid.storage.hdfs.HdfsDataSegmentPullerTest.java
@Test public void testZip() throws IOException, SegmentLoadingException { final File tmpDir = com.google.common.io.Files.createTempDir(); final File tmpFile = File.createTempFile("zipContents", ".txt", tmpDir); final Path zipPath = new Path("/tmp/testZip.zip"); final File outTmpDir = com.google.common.io.Files.createTempDir(); final URI uri = URI.create(uriBase.toString() + zipPath.toString()); try (final OutputStream stream = new FileOutputStream(tmpFile)) { ByteStreams.copy(new ByteArrayInputStream(pathByteContents), stream); }/* www. j a va 2s . co m*/ Assert.assertTrue(tmpFile.exists()); final File outFile = new File(outTmpDir, tmpFile.getName()); outFile.delete(); try (final OutputStream stream = miniCluster.getFileSystem().create(zipPath)) { CompressionUtils.zip(tmpDir, stream); } try { Assert.assertFalse(outFile.exists()); puller.getSegmentFiles(new Path(uri), outTmpDir); Assert.assertTrue(outFile.exists()); Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath())); } finally { if (tmpFile.exists()) { tmpFile.delete(); } if (outFile.exists()) { outFile.delete(); } if (outTmpDir.exists()) { outTmpDir.delete(); } if (tmpDir.exists()) { tmpDir.delete(); } } }
From source file:io.druid.segment.loading.HdfsDataSegmentPullerTest.java
@Test public void testZip() throws IOException, SegmentLoadingException { final File tmpDir = com.google.common.io.Files.createTempDir(); final File tmpFile = File.createTempFile("zipContents", ".txt", tmpDir); final Path zipPath = new Path("/tmp/testZip.zip"); final File outTmpDir = com.google.common.io.Files.createTempDir(); final URI uri = URI.create(uriBase.toString() + zipPath.toString()); try (final OutputStream stream = new FileOutputStream(tmpFile)) { ByteStreams.copy(new ByteArrayInputStream(pathByteContents), stream); }//from www . ja va 2 s . c om Assert.assertTrue(tmpFile.exists()); final File outFile = new File(outTmpDir, tmpFile.getName()); outFile.delete(); try (final OutputStream stream = miniCluster.getFileSystem().create(zipPath)) { CompressionUtils.zip(tmpDir, stream); } try { Assert.assertFalse(outFile.exists()); puller.getSegmentFiles(uri, outTmpDir); Assert.assertTrue(outFile.exists()); Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath())); } finally { if (tmpFile.exists()) { tmpFile.delete(); } if (outFile.exists()) { outFile.delete(); } if (outTmpDir.exists()) { outTmpDir.delete(); } if (tmpDir.exists()) { tmpDir.delete(); } } }
From source file:io.github.casnix.mcdropshop.util.configsys.Shops.java
public final Shops addShop(String shopName, String worldName, String x, String y, String z, Player player) { try {//from w ww.ja va2s . co m String configTable = new String(Files.readAllBytes(Paths.get("./plugins/mcDropShop/Shops.json"))); JSONParser parser = new JSONParser(); Object obj = parser.parse(configTable); JSONObject jsonObj = (JSONObject) obj; JSONArray shopList = (JSONArray) jsonObj.get("shopsArray"); // Make sure that our array isn't empty if (shopList == null) { player.sendMessage("\u00A7e<\u00A73mcDropShop : internal error\u00A7e>"); return this; } JSONObject shopObj; String shopName2; // Check if there's already a shop by that name for (int index = 0; index < shopList.size(); index++) { shopObj = (JSONObject) (shopList.get(index)); shopName2 = (String) shopObj.get("shopName"); if (shopName2.equals(shopName)) { player.sendMessage("\u00a7aThere is already a shop by that name!"); return this; } } // Set our new shop in the JSON table in memory JSONObject newShop = new JSONObject(); newShop.put("shopName", shopName); newShop.put("world", worldName); newShop.put("x", x); newShop.put("y", y); newShop.put("z", z); // Update the array in memory shopList.add(newShop); // Update the entire JSON table in memory jsonObj.put("shopsArray", shopList); // Make the shop stub JSONObject shopStub = new JSONObject(); shopStub.put("amount", "0"); shopStub.put("price", "0"); shopStub.put("type", "buy"); JSONArray newShopItemList = new JSONArray(); JSONObject SNL = new JSONObject(); SNL.put("ShopItems", newShopItemList); jsonObj.put(shopName, SNL); // Update Shops.json FileWriter shopsJSON = new FileWriter("./plugins/mcDropShop/Shops.json"); shopsJSON.write(jsonObj.toJSONString()); shopsJSON.flush(); shopsJSON.close(); player.sendMessage("\u00a7aShop added!"); return this; } catch (ParseException e) { Bukkit.getLogger().warning("[mcDropShop] Caught ParseException in addShop()"); e.printStackTrace(); } catch (FileNotFoundException e) { Bukkit.getLogger().warning("[mcDropShop] Could not find ./plugins/mcDropShop/Shops.json"); e.printStackTrace(); } catch (IOException e) { Bukkit.getLogger().warning("[mcDropShop] Caught IOException in addShop()"); e.printStackTrace(); } return this; }
From source file:com.netflix.nicobar.cassandra.CassandraArchiveRepositoryTest.java
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test/* w w w . jav a 2 s . c o m*/ public void testInsertArchive() throws IOException { JarScriptArchive jarArchive = new JarScriptArchive.Builder(testArchiveJarFile).build(); repository.insertArchive(jarArchive); Map<String, Object> columns = new HashMap<String, Object>(); Path jarFilePath; try { jarFilePath = Paths.get(jarArchive.getRootUrl().toURI()); } catch (URISyntaxException e) { throw new IOException(e); } ScriptModuleSpec moduleSpec = jarArchive.getModuleSpec(); String serialized = config.getModuleSpecSerializer().serialize(moduleSpec); byte[] jarBytes = Files.readAllBytes(jarFilePath); columns.put(Columns.shard_num.name(), repository.calculateShardNum(moduleSpec.getModuleId())); columns.put(Columns.last_update.name(), jarArchive.getCreateTime()); columns.put(Columns.archive_content.name(), jarBytes); columns.put(Columns.archive_content_hash.name(), repository.calculateHash(jarBytes)); columns.put(Columns.module_spec.name(), serialized); ArgumentCaptor<String> argument1 = ArgumentCaptor.forClass(String.class); ArgumentCaptor<Map> argument2 = ArgumentCaptor.forClass(Map.class); verify(gateway).upsert(argument1.capture(), argument2.capture()); assertEquals(moduleSpec.getModuleId().toString(), argument1.getValue()); Map columnMap = argument2.getValue(); assertEquals(repository.calculateShardNum(moduleSpec.getModuleId()), columnMap.get(Columns.shard_num.name())); assertTrue(Arrays.equals(jarBytes, (byte[]) columnMap.get(Columns.archive_content.name()))); assertTrue(Arrays.equals(repository.calculateHash(jarBytes), (byte[]) columnMap.get(Columns.archive_content_hash.name()))); assertEquals(serialized, (String) columnMap.get(Columns.module_spec.name())); assertEquals(jarArchive.getCreateTime(), (long) columnMap.get(Columns.last_update.name())); }
From source file:com.crushpaper.Main.java
/** Returns the contents of the file as a string or null. */ static String readFile(File file) { byte[] encoded; try {/*www . j a v a2 s .c om*/ encoded = Files.readAllBytes(file.toPath()); } catch (IOException e) { return null; } return new String(encoded, Charset.forName("UTF-8")); }
From source file:com.alehuo.wepas2016projekti.service.InitService.java
/** * Lis kuvan//from ww w.j av a 2 s . c o m * * @param fPath Tiedoston sijainti * @param type Tyyppi * @param type2 Tyyppi 2 * @param description Kuvaus * @param poster Lisj * @param resize Pienennetnk kuvaa vai ei? * @throws IOException */ public void addImage(String fPath, String type, String type2, String description, String poster, boolean resize) throws IOException { Path path = Paths.get(fPath); Image i = new Image(); i.setImageContentType(type); //Jos kuva halutaan pienent if (resize) { i.setImageData(resizeImage(Files.readAllBytes(path), type2, widthHeight)); } else { //Muuten, lis kuva sellaisenaan i.setImageData(Files.readAllBytes(path)); } i.setDescription(description); i.setImageOwner(userService.getUserByUsername(poster)); imageRepo.save(i); }
From source file:org.eclipse.vorto.remoterepository.internal.dao.FilesystemModelDAO.java
private ModelContent getModelContent(Path file) { ModelType modelType = getModelType(file.toString()); try {// ww w. j a v a 2 s.com return new ModelContent(modelType, Files.readAllBytes(file)); } catch (IOException e) { throw new RuntimeException(e); } }