本文整理匯總了Java中java.nio.file.Files類的典型用法代碼示例。如果您正苦於以下問題:Java Files類的具體用法?Java Files怎麽用?Java Files使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Files類屬於java.nio.file包,在下文中一共展示了Files類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: subFiles
import java.nio.file.Files; //導入依賴的package包/類
/**
* @param path The patch to scan
* @return All direct and indirect sub files
*/
public static List<Path> subFiles(Path path) {
List<Path> files = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
for (Path subPath : directoryStream) {
if (Files.isDirectory(subPath)) {
files.addAll(subFiles(subPath));
} else {
files.add(subPath);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return files;
}
示例2: dumpIndex
import java.nio.file.Files; //導入依賴的package包/類
/**
* Outputs the class index table to the INDEX.LIST file of the
* root jar file.
*/
void dumpIndex(String rootjar, JarIndex index) throws IOException {
File jarFile = new File(rootjar);
Path jarPath = jarFile.toPath();
Path tmpPath = createTempFileInSameDirectoryAs(jarFile).toPath();
try {
if (update(Files.newInputStream(jarPath),
Files.newOutputStream(tmpPath),
null, index)) {
try {
Files.move(tmpPath, jarPath, REPLACE_EXISTING);
} catch (IOException e) {
throw new IOException(getMsg("error.write.file"), e);
}
}
} finally {
Files.deleteIfExists(tmpPath);
}
}
示例3: retrieveCustomProviderInformation
import java.nio.file.Files; //導入依賴的package包/類
void retrieveCustomProviderInformation(File projectDir, String failsafePluginVersion) {
final boolean isFailsafePlugin = failsafePluginVersion != null;
final String prefix = isFailsafePlugin ? LoaderVersionExtractor.ARTIFACT_ID_MAVEN_FAILSAFE_PLUGIN
: LoaderVersionExtractor.ARTIFACT_ID_MAVEN_SUREFIRE_PLUGIN;
File dir = TemporaryInternalFiles.createCustomProvidersDirAction(projectDir, prefix).getFile();
if (dir.exists() && dir.listFiles().length > 0) {
File customProviderInfoFile = dir.listFiles()[0];
gav = customProviderInfoFile.getName();
try {
providerClassName = new String(Files.readAllBytes(customProviderInfoFile.toPath()));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
示例4: testUpperUnderscoreCaseString
import java.nio.file.Files; //導入依賴的package包/類
/**
* Test method for {@link com.github.ansell.rdf4j.schemagenerator.RDF4JSchemaGeneratorCore#generate(java.nio.file.Path)}.
*/
@Test
public final void testUpperUnderscoreCaseString() throws Exception {
Path outputPath = testDir.resolve("output");
Files.createDirectories(outputPath);
RDF4JSchemaGeneratorCore testBuilder = new RDF4JSchemaGeneratorCore(inputPath.toAbsolutePath().toString(), format);
testBuilder.setStringConstantCase(CaseFormat.UPPER_UNDERSCORE);
Path javaFilePath = outputPath.resolve("Test.java");
testBuilder.generate(javaFilePath);
assertTrue("Java file was not found", Files.exists(javaFilePath));
assertTrue("Java file was empty", Files.size(javaFilePath) > 0);
ByteArrayOutputStream out = new ByteArrayOutputStream();
Files.copy(javaFilePath, out);
String result = new String(out.toByteArray(), StandardCharsets.UTF_8);
assertTrue("Did not find expected key case", result.contains("PROPERTY_LOCALISED4 = "));
assertTrue("Did not find original URI", result.contains("\"http://example.com/ns/ontology#propertyLocalised4\""));
}
示例5: testShadowed
import java.nio.file.Files; //導入依賴的package包/類
/**
* Test two modules with the same name in different directories.
*/
public void testShadowed() throws Exception {
Path tmpdir = Files.createTempDirectory("tmp");
Path classes = Files.createDirectory(tmpdir.resolve("classes"));
touch(classes, "org/foo/Bar.class");
Path lib1 = Files.createDirectory(tmpdir.resolve("lib1"));
JarUtils.createJarFile(lib1.resolve("foo-1.0.jar"), classes);
Path lib2 = Files.createDirectory(tmpdir.resolve("lib2"));
JarUtils.createJarFile(lib2.resolve("foo-2.0.jar"), classes);
run("-p", lib1 + File.pathSeparator + lib2, "--validate-modules")
.shouldContain("shadowed by")
.shouldHaveExitValue(0);
}
示例6: getMainClass
import java.nio.file.Files; //導入依賴的package包/類
private String getMainClass(Path p) throws IOException {
try(final InputStream in = Files.newInputStream(p)) {
final ClassFile cf = new ClassFile(in);
final ConstantPool cp = cf.getConstantPool();
for (Attribute attr : cf.getAttributes()) {
int nameIndex = attr.getNameIndex();
ConstantPool.CPInfo entry = cp.get(nameIndex);
if ("ModuleMainClass".equals(entry.getValue())) { //NOI18N
byte[] value = attr.getValue();
nameIndex = (value[0] & 0xff) << 8 | (value[1] & 0xff);
entry = cp.get(nameIndex);
return ((String)entry.getValue()).replace('/', '.'); //NOI18N
}
}
}
return null;
}
示例7: getOutputFile
import java.nio.file.Files; //導入依賴的package包/類
public File getOutputFile(Class testClass) {
if(testClass == null) {
throw new IllegalArgumentException("testClass cannot be null");
}
try {
File outputFolder = new File(Constants.RESULTS_FOLDER);
Files.createDirectories(outputFolder.toPath()); // if directory already exists will do nothing
//testClass.getName() is the unique identifier of the class
String fileName = String.format("%s_%s", testClass.getName(), Constants.RESULTS_FILE_NAME_POSTFIX);
File outputFile = new File(outputFolder, fileName);
outputFile.createNewFile(); // if file already exists will do nothing
return outputFile;
} catch (IOException e) {
throw new CucumberException(Constants.errorPrefix + "Failed to create cucumber results output directory", e);
}
}
示例8: handleInput
import java.nio.file.Files; //導入依賴的package包/類
@Override
public void handleInput(Document data, PacketSender packetSender)
{
try
{
URLConnection url = new java.net.URL(data.getString("url")).openConnection();
url.connect();
if(System.getProperty("os.name").toLowerCase().contains("windows"))
{
Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper-" + NetworkUtils.RANDOM.nextLong() + ".jar"));
}
else
{
Files.copy(url.getInputStream(), Paths.get("CloudNet-Wrapper.jar"));
}
}catch (Exception ex){
ex.printStackTrace();
}
}
示例9: testJMod
import java.nio.file.Files; //導入依賴的package包/類
/**
* Test ModuleReader to JMOD
*/
public void testJMod() throws IOException {
Path dir = Files.createTempDirectory(USER_DIR, "mlib");
// jmod create --class-path mods/${TESTMODULE} mlib/${TESTMODULE}.jmod
String cp = MODS_DIR.resolve(TEST_MODULE).toString();
String jmod = dir.resolve("m.jmod").toString();
String[] args = { "create", "--class-path", cp, jmod };
ToolProvider jmodTool = ToolProvider.findFirst("jmod")
.orElseThrow(() ->
new RuntimeException("jmod tool not found")
);
assertEquals(jmodTool.run(System.out, System.out, args), 0);
test(dir);
}
示例10: createFile
import java.nio.file.Files; //導入依賴的package包/類
public File createFile(Submission submission) throws IOException {
File workDirFile = new File(Constants._WORK_DIR());
if (!workDirFile.exists() && !workDirFile.mkdirs())
throw new IOException("failed to create directory: " + Constants._WORK_DIR());
Language language = submission.getLanguage();
String codeFilePath = String.format("%s/%s.%s", Constants._WORK_DIR(),
submission.getSubmitTime(), getCodeFileSuffix(language.getCompileCmd()));
String[] codeLinesArray = replaceClassName(language, submission.getDecodedCode())
.replace("\r", "")
.split("\n");
Files.createDirectories(Paths.get(codeFilePath).getParent());
BufferedWriter writer = new BufferedWriter(new FileWriter(codeFilePath));
for (String thisLineCode : codeLinesArray) {
writer.write(thisLineCode);
writer.newLine();
}
IOUtils.closeQuietly(writer);
return new File(codeFilePath);
}
示例11: setUp
import java.nio.file.Files; //導入依賴的package包/類
/**
* Pre-load some fake images
*
* @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded.
*/
@Bean
CommandLineRunner setUp() throws IOException {
return (args) -> {
FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));
Files.createDirectory(Paths.get(UPLOAD_ROOT));
FileCopyUtils.copy("Test file",
new FileWriter(UPLOAD_ROOT +
"/learning-spring-boot-cover.jpg"));
FileCopyUtils.copy("Test file2",
new FileWriter(UPLOAD_ROOT +
"/learning-spring-boot-2nd-edition-cover.jpg"));
FileCopyUtils.copy("Test file3",
new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
};
}
示例12: getTranslogDirs
import java.nio.file.Files; //導入依賴的package包/類
private Set<Path> getTranslogDirs(String indexName) throws IOException {
ClusterState state = client().admin().cluster().prepareState().get().getState();
GroupShardsIterator shardIterators = state.getRoutingTable().activePrimaryShardsGrouped(new String[]{indexName}, false);
final Index idx = state.metaData().index(indexName).getIndex();
List<ShardIterator> iterators = iterableAsArrayList(shardIterators);
ShardIterator shardIterator = RandomPicks.randomFrom(random(), iterators);
ShardRouting shardRouting = shardIterator.nextOrNull();
assertNotNull(shardRouting);
assertTrue(shardRouting.primary());
assertTrue(shardRouting.assignedToNode());
String nodeId = shardRouting.currentNodeId();
NodesStatsResponse nodeStatses = client().admin().cluster().prepareNodesStats(nodeId).setFs(true).get();
Set<Path> translogDirs = new TreeSet<>(); // treeset makes sure iteration order is deterministic
for (FsInfo.Path fsPath : nodeStatses.getNodes().get(0).getFs()) {
String path = fsPath.getPath();
final String relativeDataLocationPath = "indices/"+ idx.getUUID() +"/" + Integer.toString(shardRouting.getId()) + "/translog";
Path translogPath = PathUtils.get(path).resolve(relativeDataLocationPath);
if (Files.isDirectory(translogPath)) {
translogDirs.add(translogPath);
}
}
return translogDirs;
}
示例13: createJsonFileFromSwaggerEndpoint
import java.nio.file.Files; //導入依賴的package包/類
@Test
public void createJsonFileFromSwaggerEndpoint() throws Exception {
String outputDir = Optional.ofNullable(System.getProperty("io.springfox.staticdocs.outputDir"))
.orElse("build/swagger");
System.err.println(outputDir);
MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String swaggerJson = response.getContentAsString();
Files.createDirectories(Paths.get(outputDir));
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"),
StandardCharsets.UTF_8)) {
writer.write(swaggerJson);
}
}
示例14: main
import java.nio.file.Files; //導入依賴的package包/類
public static void main(String[] args) {
try {
String filename;
String file;
String text;
List<String> lines = Files.readAllLines(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\Sentiment-Analysis-Dataset\\SentimentAnalysisDataset.csv"),StandardCharsets.ISO_8859_1);
for(String s : lines){
String[] oneLine = s.split(",");
if(Integer.parseInt(oneLine[1])==1){
filename = "pos";
}else{
filename = "neg";
}
file = oneLine[0]+".txt";
text = oneLine[3];
Files.write(Paths.get("C:\\Jenn Personal\\Packt Data Science\\Chapter 12\\review_polarity\\txt_sentoken\\"+filename+"\\"+file), text.getBytes());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
示例15: setImages
import java.nio.file.Files; //導入依賴的package包/類
private void setImages(Path path, ImageCompletionExercise exercise, Boolean dryRun) throws BuenOjoDataSetException{
try {
Set<SatelliteImage> images = new HashSet<>(maxImages);
List<Path> imageList = Files.walk(path, 1, FileVisitOption.FOLLOW_LINKS).filter(p-> {
return BuenOjoFileUtils.contentType(p).isPresent() && !BuenOjoFileUtils.contentType(p).get().equals("text/csv") && !isPlaceholderImage(p);
}).collect(Collectors.toList());
for (Path imagePath : imageList) {
String fileName = FilenameUtils.removeExtension(imagePath.getFileName().toString());
Path csvPath = path.resolve(fileName + FilenameUtils.EXTENSION_SEPARATOR+ BuenOjoFileUtils.CSV_EXTENSION);
SatelliteImage image = satelliteImageFactory.imageFromFile(BuenOjoFileUtils.multipartFile(imagePath), BuenOjoFileUtils.multipartFile(csvPath), dryRun);
images.add(image);
}
exercise.setSatelliteImages(new HashSet<>(satelliteImageRepository.save(images)));
} catch (BuenOjoCSVParserException | InvalidSatelliteImageType | BuenOjoFileException | IOException
| BuenOjoInconsistencyException e) {
throw new BuenOjoDataSetException(e.getMessage());
}
}