Java Code Examples for java.nio.file.Files.readAllBytes()

The following are Jave code examples for showing how to use readAllBytes() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: echo   File: TempSource.java   View Source Code Vote up 9 votes
@Override
public Iterable<Pair<String, String>> get() {
	List<Pair<String,String>> list = new ArrayList<Pair<String,String>>();
	File dir = new File(sourceDir);
	if(dir.isDirectory())
	{
		File[] files = dir.listFiles();
		for(File file:files) {
				byte[] bytes;
				try {
					bytes = Files.readAllBytes(file.toPath());
					String content =  new String(bytes,"UTF-8");
					Pair<String, String> e = Pair.of(file.getName(), content);
					list.add(e);
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		}
	}
	return list;
}
 
Example 2
Project: TensorFlow-models4j   File: Inception.java   View Source Code Vote up 7 votes
public Inception(String graphPath, String labelsPath) throws IOException{
    graphDef = Files.readAllBytes(Paths.get(graphPath));
    labels = Files.readAllLines(Paths.get(labelsPath));

    Graph g = new Graph();
    s = new Session(g);
    GraphBuilder b = new GraphBuilder(g);
    // - The model was trained with images scaled to 224x224 pixels.
    // - The colors, represented as R, G, B in 1-byte each were converted to
    //   float using (value - Mean)/Scale.
    final int H = 224;
    final int W = 224;
    final float mean = 117f;
    final float scale = 1f;
    output = b.div(
                b.sub(
                    b.resizeBilinear(
                            b.expandDims(
                                    b.cast(b.decodeJpeg(b.placeholder("input", DataType.STRING), 3), DataType.FLOAT),
                                    b.constant("make_batch", 0)),
                            b.constant("size", new int[] {H, W})),
                    b.constant("mean", mean)),
                b.constant("scale", scale));
}
 
Example 3
Project: TOSCAna   File: ZipUtilityTest.java   View Source Code Vote up 6 votes
private void validateFolderStructure(File current, File currRoot, File compRoot) throws Exception {
    if (current.isFile()) {
        String relative = getRelativePath(currRoot, current);
        File comp = new File(compRoot, relative);
        log.trace("Comparing files {} and {}", current.getAbsolutePath(), comp.getAbsolutePath());
        assertTrue(comp.isFile() && comp.length() == current.length());
        byte[] currentData = Files.readAllBytes(current.toPath());
        byte[] compareData = Files.readAllBytes(comp.toPath());
        for (int i = 0; i < currentData.length; i++) {
            assertTrue("Mismatch at " + i, currentData[i] == compareData[i]);
        }
    } else {
        for (File file : current.listFiles()) {
            validateFolderStructure(file, currRoot, compRoot);
        }
    }
}
 
Example 4
Project: light-codegen   File: Cli.java   View Source Code Vote up 6 votes
public void run() {
    System.out.printf("%s %s %s %s", framework, model, config, output);
    FrameworkRegistry registry = FrameworkRegistry.getInstance();
    Set<String> frameworks = registry.getFrameworks();
    if(frameworks.contains(framework)) {
        Generator generator = registry.getGenerator(framework);
        try {
            Object anyModel = null;
            // model can be empty in some cases.
            if(model != null) {
                // check if model is json or not before loading.
                if(model.endsWith("json")) {
                    if(isUrl(model)) {
                        anyModel = JsonIterator.deserialize(urlToByteArray(new URL(model)));
                    } else {
                        anyModel = JsonIterator.deserialize(Files.readAllBytes(Paths.get(model)));
                    }
                } else {
                    if(isUrl(model)) {
                        anyModel = new String(urlToByteArray(new URL(model)), StandardCharsets.UTF_8);
                    } else {
                        anyModel = new String(Files.readAllBytes(Paths.get(model)), StandardCharsets.UTF_8);
                    }
                }
            }

            Any anyConfig = null;
            if(isUrl(config)) {
                anyConfig = JsonIterator.deserialize(urlToByteArray(new URL(config)));
            } else {
                anyConfig = JsonIterator.deserialize(Files.readAllBytes(Paths.get(config)));
            }
           generator.generate(output, anyModel, anyConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        System.out.printf("Invalid framework %s", framework);
    }
}
 
Example 5
Project: Enjin-Coin-Java-SDK   File: FileUtilsTest.java   View Source Code Vote up 6 votes
@Test
public void testGetFileContents_BytesIsEmpty() throws Exception {
    String filePath = "c:\\temp\\file.txt";

    Path mockPath = PowerMockito.mock(Path.class);
    PowerMockito.mockStatic(Paths.class);
    PowerMockito.mockStatic(Files.class);

    Mockito.when(Paths.get(Mockito.anyString())).thenReturn(mockPath);
    Mockito.when(Files.readAllBytes(Mockito.isA(Path.class))).thenReturn("".getBytes());

    String fileContents = FileUtils.getFileContents(filePath);
    assertThat(fileContents).isNull();

    PowerMockito.verifyStatic(Paths.class);
    Paths.get(Mockito.anyString());
    PowerMockito.verifyStatic(Files.class);
    Files.readAllBytes(Mockito.isA(Path.class));
}
 
Example 6
Project: mturk-code-samples   File: CreateHITSample.java   View Source Code Vote up 5 votes
private HITInfo createHIT(final String questionXmlFile) throws IOException {

		// QualificationRequirement: Locale IN (US, CA)
		QualificationRequirement localeRequirement = new QualificationRequirement();
		localeRequirement.setQualificationTypeId("00000000000000000071");
		localeRequirement.setComparator(Comparator.In);
		List<Locale> localeValues = new ArrayList<>();
		localeValues.add(new Locale().withCountry("US"));
		localeValues.add(new Locale().withCountry("CA"));
		localeRequirement.setLocaleValues(localeValues);
		localeRequirement.setRequiredToPreview(true);

		// Read the question XML into a String
		String questionSample = new String(Files.readAllBytes(Paths.get(questionXmlFile)));

		CreateHITRequest request = new CreateHITRequest();
		request.setMaxAssignments(10);
		request.setLifetimeInSeconds(600L);
		request.setAssignmentDurationInSeconds(600L);
		// Reward is a USD dollar amount - USD$0.20 in the example below
		request.setReward("0.20");
		request.setTitle("Answer a simple question");
		request.setKeywords("question, answer, research");
		request.setDescription("Answer a simple question");
		request.setQuestion(questionSample);
		request.setQualificationRequirements(Collections.singletonList(localeRequirement));

		CreateHITResult result = client.createHIT(request);
		return new HITInfo(result.getHIT().getHITId(), result.getHIT().getHITTypeId());
	}
 
Example 7
Project: openjdk-jdk10   File: CustomSystemClassLoader.java   View Source Code Vote up 5 votes
private Class<?> defineFinderClass(String name)
    throws ClassNotFoundException {
    final Object obj = getClassLoadingLock(name);
    synchronized(obj) {
        if (finderClass != null) return finderClass;

        URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.getPath(), name+".class");
        if (file.canRead()) {
            try {
                byte[] b = Files.readAllBytes(file.toPath());
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                finderClass = defineClass(
                        name, b, 0, b.length, new ProtectionDomain(
                        this.getClass().getProtectionDomain().getCodeSource(),
                        perms));
                System.out.println("Loaded " + name);
                return finderClass;
            } catch (Throwable ex) {
                ex.printStackTrace();
                throw new ClassNotFoundException(name, ex);
            }
        } else {
            throw new ClassNotFoundException(name,
                    new IOException(file.toPath() + ": can't read"));
        }
    }
}
 
Example 8
Project: clearwsd   File: OntoNotesConverter.java   View Source Code Vote up 5 votes
/**
 * Read a list of {@link VerbNetInstance instances} from OntoNotes files in a given {@link Path}.
 *
 * @param directory OntoNotes path
 * @return list of sense instances
 */
public List<VerbNetInstance> getInstances(Path directory) {
    Predicate<String> filter = Pattern.compile(lemmafilter).asPredicate();
    List<VerbNetInstance> instances = new ArrayList<>();
    try {
        for (Path path : getParseFiles(directory)) {
            Path sensePath = Paths.get(path.toString().replaceAll(parseExt + "$", senseExt));
            if (Files.exists(sensePath)) {
                String trees = new String(Files.readAllBytes(path));
                Map<Integer, String> sentenceMap = new HashMap<>();
                for (TreebankTreeNode treeNode : parse(trees)) {
                    sentenceMap.put(sentenceMap.size(), treeNode.toString());
                }
                String senses = new String(Files.readAllBytes(sensePath));
                for (String senseLine : senses.split("[\\r\\n]+")) {
                    String[] fields = senseLine.split(" ");
                    String lemma = fields[3];
                    if (!filter.test(lemma)) {
                        continue;
                    }
                    VerbNetInstance instance = new VerbNetInstance()
                            .path(fields[0])
                            .sentence(Integer.parseInt(fields[1]))
                            .token(Integer.parseInt(fields[2]))
                            .lemma(lemma)
                            .label(fields.length == 6 ? fields[5] : fields[4]);
                    instance.originalText(sentenceMap.getOrDefault(instance.sentence(), ""));
                    instances.add(instance);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("Error reading instances: " + e.getMessage(), e);
    }
    return instances;
}
 
Example 9
Project: dataset-lib   File: StringDataStore.java   View Source Code Vote up 5 votes
public void start(){
StringBuilder b;
Path p;
File[] storageLocations = new File[storageTiering.length];
for (int i = 0; i < storageTiering.length; i++) {
    storageLocations[i] = new File(storageTiering[i]);
}  
Runnable clean=()->{
    for (int i = 0; i < index.length(); i++) {
        for (int z = 0; z < storageTiering.length; z++) {
            if (a.get(i).getAccessAverage() < thresholds[z]) {
                b.append(storageTiering[i]);
                b.append("/");
                if (a.get(i).getLocationTier() != 0) {
                    String str = new String(Files.readAllBytes( Paths.get( index.get(i).getPath())));
                    dataStore.put(a.get(i), str);
                    File file=new File(index.get(a).getPath());
                    file.delete();
                }
                b.append(a.get(i).getTitle());
                b.append(".txt");
                p.get(b.toString());
                Files.write(p, dataStore.get(a.get(i)).getBytes());
                index.get(i).setPath(b.toString());
                b.setLength(0);
                index.get(i).setLocationTier(z);
                }
            }
        }
    };
ScheduledExecutorService service=Executors.newScheduledThreadPool(1);
ScheduledFuture future=service.schedule(clean, (long)checkInterval,unit);
}
 
Example 10
Project: carnotzet   File: ResourcesManagerTest.java   View Source Code Vote up 5 votes
private String readFile(Path root, String path) throws IOException {
	return new String(Files.readAllBytes(root.resolve(path)), "UTF-8");
}
 
Example 11
Project: inception-serving-sb   File: AppControllerTest.java   View Source Code Vote up 5 votes
@Test
public void classifyImageOk() throws Exception {
    byte[] bytes = Files.readAllBytes(Paths.get(resourceLoader.getResource("classpath:boat.jpg").getURI()));
    MockMultipartFile file = new MockMultipartFile("file", "boat.jpg", "image/jpeg", bytes);

    String blowfish = this.mockMvc.perform(
        fileUpload("/api/classify")
            .file(file))
        .andDo(document("classify-image-ok/{step}",
            preprocessRequest(prettyPrint(), replacePattern(Pattern.compile(".*"), "...boat.jpg multipart binary contents...")),
            preprocessResponse(prettyPrint())))
        .andExpect(status().isOk())
        .andExpect(jsonPath("label", notNullValue()))
        .andExpect(jsonPath("probability", notNullValue()))
        .andReturn().getResponse().getContentAsString();
}
 
Example 12
Project: xrpc   File: X509CertificateGenerator.java   View Source Code Vote up 5 votes
public static DerKeySpec parseDerKeySpec(Path path) {
  String rawKeyString = null;
  try {
    rawKeyString =
        new String(Files.readAllBytes(path.toAbsolutePath()), XrpcConstants.DEFAULT_CHARSET);
  } catch (IOException e) {
    // TODO(JR): This is bad practice, we should fix this more elegantly
    throw new RuntimeException(
        new GeneralSecurityException("Could not parse a PKCS1 private key."));
  }

  return parseDerKeySpec(rawKeyString);
}
 
Example 13
Project: omero-ms-queue   File: FileOpsWriteNewTest.java   View Source Code Vote up 5 votes
@Test
public void writeEmptyFile() throws IOException {
    Path target = pathInTempDir("x");
    FileOps.writeNew(target, out -> {});

    byte[] content = Files.readAllBytes(target);
    assertNotNull(content);
    assertThat(content.length, is(0));
}
 
Example 14
Project: JITRAX   File: FileDialog.java   View Source Code Vote up 5 votes
/**
 * Returns as a string the content of a chosen file.
 * @param dialogTitle
 * @return
 */
public String importFileContent(String dialogTitle) {
	JFileChooser fileChooser = new JFileChooser();
	String filePath;
	int userSelection;
	
	fileChooser.setDialogTitle(dialogTitle);
	userSelection = fileChooser.showSaveDialog(null);
	
	if (userSelection == JFileChooser.APPROVE_OPTION) {
		filePath = fileChooser.getSelectedFile().getAbsolutePath();
		
		// Read file
		byte[] encoded;
		
		try {
			encoded = Files.readAllBytes(Paths.get(filePath));
			return new String(encoded, StandardCharsets.UTF_8);
		}
		
		catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	return null;
}
 
Example 15
Project: dss-demonstrations   File: RestDocumentationApp.java   View Source Code Vote up 4 votes
private byte[] toByteArray(File file) throws IOException {
	return Files.readAllBytes(file.toPath());
}
 
Example 16
Project: spring-cloud-release-tools   File: AcceptanceTests.java   View Source Code Vote up 4 votes
private String emailTemplateContents() throws URISyntaxException, IOException {
	return new String(Files.readAllBytes(emailTemplate().toPath()));
}
 
Example 17
Project: ForgeHax   File: FirstTimeRunningService.java   View Source Code Vote up 4 votes
private static final String getOnceFileVersion() {
    if(STARTUP_ONCE.exists()) try {
        return new String(Files.readAllBytes(STARTUP_ONCE.toPath()));
    } catch (Throwable t) {}
    return Strings.EMPTY;
}
 
Example 18
Project: spring-cloud-release-tools   File: ProjectBuilderTests.java   View Source Code Vote up 4 votes
private String asString(File file) throws IOException {
	return new String(Files.readAllBytes(file.toPath()));
}
 
Example 19
Project: nordvisa_calendar   File: ImageControllerTest.java   View Source Code Vote up 4 votes
@Test
public void getImage() throws Exception {
    Image image = mock(Image.class);

    byte[] file = Files.readAllBytes(new File(resources + "test.jpg").toPath());

    when(image.getFile()).thenReturn(file);
    when(image.getPath()).thenReturn("123456789abcdef");
    when(image.getName()).thenReturn("test.jpg");

    when(dao.getImage("123456789abcdef", "test.jpg")).thenReturn(image);

    assertEquals(file, sut.getImage("123456789abcdef", "test.jpg").getBody());

    verify(dao, times(1)).getImage("123456789abcdef", "test.jpg");
}
 
Example 20
Project: hygene   File: AppData.java   View Source Code Vote up 2 votes
/**
 * Reads the given file and saves its contents to a {@link String}s.
 *
 * @param file the file to be read from
 * @return a {@link String}s, representing the contents of the file
 * @throws IOException if an exception occurs during file IO
 */
private static String readFile(final File file) throws IOException {
    final byte[] rawContents = Files.readAllBytes(Paths.get(file.getPath()));
    return new String(rawContents, FILE_ENCODING);
}