本文整理匯總了Java中java.nio.file.Files.readAllBytes方法的典型用法代碼示例。如果您正苦於以下問題:Java Files.readAllBytes方法的具體用法?Java Files.readAllBytes怎麽用?Java Files.readAllBytes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.nio.file.Files
的用法示例。
在下文中一共展示了Files.readAllBytes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: get
import java.nio.file.Files; //導入方法依賴的package包/類
@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;
}
示例2: Inception
import java.nio.file.Files; //導入方法依賴的package包/類
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));
}
示例3: validateFolderStructure
import java.nio.file.Files; //導入方法依賴的package包/類
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);
}
}
}
示例4: run
import java.nio.file.Files; //導入方法依賴的package包/類
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);
}
}
示例5: testGetFileContents_BytesIsEmpty
import java.nio.file.Files; //導入方法依賴的package包/類
@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));
}
示例6: createHIT
import java.nio.file.Files; //導入方法依賴的package包/類
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());
}
示例7: defineFinderClass
import java.nio.file.Files; //導入方法依賴的package包/類
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"));
}
}
}
示例8: getInstances
import java.nio.file.Files; //導入方法依賴的package包/類
/**
* 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;
}
示例9: start
import java.nio.file.Files; //導入方法依賴的package包/類
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);
}
示例10: readFile
import java.nio.file.Files; //導入方法依賴的package包/類
private String readFile(Path root, String path) throws IOException {
return new String(Files.readAllBytes(root.resolve(path)), "UTF-8");
}
示例11: classifyImageOk
import java.nio.file.Files; //導入方法依賴的package包/類
@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();
}
示例12: parseDerKeySpec
import java.nio.file.Files; //導入方法依賴的package包/類
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);
}
示例13: writeEmptyFile
import java.nio.file.Files; //導入方法依賴的package包/類
@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));
}
示例14: importFileContent
import java.nio.file.Files; //導入方法依賴的package包/類
/**
* 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;
}
示例15: toByteArray
import java.nio.file.Files; //導入方法依賴的package包/類
private byte[] toByteArray(File file) throws IOException {
return Files.readAllBytes(file.toPath());
}