当前位置: 首页>>代码示例>>Java>>正文


Java Files.createFile方法代码示例

本文整理汇总了Java中java.nio.file.Files.createFile方法的典型用法代码示例。如果您正苦于以下问题:Java Files.createFile方法的具体用法?Java Files.createFile怎么用?Java Files.createFile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.file.Files的用法示例。


在下文中一共展示了Files.createFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toFile

import java.nio.file.Files; //导入方法依赖的package包/类
/**
 * 将数据库的数据导出为CSV
 *
 * @param file        导出的文件
 * @param sourceClass 读取数据库数据时对应的Bean
 * @param targetClass 写入文件时对应的Bean
 * @param sourceList  数据库查到的数据
 */
@SneakyThrows(IOException.class)
public static <F, T> void toFile(Path file, Class<F> sourceClass, Class<T> targetClass, List<F> sourceList) {
    if (Files.notExists(file)) {
        Files.createFile(file);
    }
    Copier<F, T> copier = Copiers.create(sourceClass, targetClass);
    List<T> data = sourceList.parallelStream().map(copier::copy).collect(Collectors.toList());
    //List转换CSV处理器
    BeanWriterProcessor<T> writerProcessor = new BeanWriterProcessor<>(targetClass);
    writerProcessor.setStrictHeaderValidationEnabled(true);
    //CSV写入设置
    CsvWriterSettings settings = Csv.writeExcel();
    //设置处理器
    settings.setRowWriterProcessor(writerProcessor);
    try (OutputStream os = Files.newOutputStream(file, CREATE, TRUNCATE_EXISTING, WRITE);
         OutputStreamWriter osw = new OutputStreamWriter(os)) {
        CsvWriter writer = new CsvWriter(osw, settings);
        writer.processRecordsAndClose(data);
    }
}
 
开发者ID:drtrang,项目名称:maven-archetype-springboot,代码行数:29,代码来源:CsvUtils.java

示例2: save

import java.nio.file.Files; //导入方法依赖的package包/类
private void save() {
    try {
        Path p = Options.path.resolve("recentfiles");
        Log.info("Save recent files to file: " + p);
        if (Files.notExists(p)) {
            Files.createFile(p);
        }
        try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(p))) {
            for (RecentFile recentFile : list) {
                pw.println(recentFile);
            }
        }
    } catch (IOException e) {
        Log.error(e);
    }
}
 
开发者ID:Glavo,项目名称:ClassViewer,代码行数:17,代码来源:RecentFiles.java

示例3: superupdate_shouldCopyNewMETSFileCorrectly

import java.nio.file.Files; //导入方法依赖的package包/类
/**
 * @see MetsIndexer#superupdate(Path,Path,DataRepository)
 * @verifies copy new METS file correctly
 */
@Test
public void superupdate_shouldCopyNewMETSFileCorrectly() throws Exception {
    Path viewerRootFolder = Paths.get("build/viewer");
    Assert.assertTrue(Files.isDirectory(viewerRootFolder));
    Path updatedMetsFolder = Paths.get(viewerRootFolder.toAbsolutePath().toString(), "updated_mets");
    Assert.assertTrue(Files.isDirectory(updatedMetsFolder));

    Path metsFile = Paths.get(viewerRootFolder.toAbsolutePath().toString(), "PPN123.UPDATED");
    Files.createFile(metsFile);
    Assert.assertTrue(Files.isRegularFile(metsFile));

    DataRepository dataRepository = new DataRepository(viewerRootFolder.toAbsolutePath().toString());
    MetsIndexer.superupdate(metsFile, updatedMetsFolder, dataRepository);

    Path newMetsFile = Paths.get(dataRepository.getDir(DataRepository.PARAM_INDEXED_METS).toAbsolutePath().toString(), "PPN123.xml");
    Assert.assertTrue(Files.isRegularFile(newMetsFile));
}
 
开发者ID:intranda,项目名称:goobi-viewer-indexer,代码行数:22,代码来源:MetsIndexerTest.java

示例4: testMissingDescriptor

import java.nio.file.Files; //导入方法依赖的package包/类
public void testMissingDescriptor() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Files.createFile(pluginDir.resolve("fake.yml"));
    String pluginZip = writeZip(pluginDir, "elasticsearch");
    NoSuchFileException e = expectThrows(NoSuchFileException.class, () -> installPlugin(pluginZip, env.v1()));
    assertTrue(e.getMessage(), e.getMessage().contains("plugin-descriptor.properties"));
    assertInstallCleaned(env.v2());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:10,代码来源:InstallPluginCommandTests.java

示例5: testOutputIsFile

import java.nio.file.Files; //导入方法依赖的package包/类
public void testOutputIsFile() throws IOException {
    // output == file
    Path image = helper.createNewImageDir("failure4");
    Files.createFile(image);
    JImageGenerator.getJLinkTask()
            .modulePath(helper.defaultModulePath())
            .output(image)
            .addMods("leaf1")
            .call().assertFailure("Error: directory already exists: .*failure4.image(\n|\r|.)*");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:JLinkNegativeTest.java

示例6: testBin

import java.nio.file.Files; //导入方法依赖的package包/类
public void testBin() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Path binDir = pluginDir.resolve("bin");
    Files.createDirectory(binDir);
    Files.createFile(binDir.resolve("somescript"));
    String pluginZip = createPlugin("fake", pluginDir);
    installPlugin(pluginZip, env.v1());
    assertPlugin("fake", pluginDir, env.v2());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:11,代码来源:InstallPluginCommandTests.java

示例7: create

import java.nio.file.Files; //导入方法依赖的package包/类
/**
 * Creates the given file or directory set in previous steps. If the type is a file, then the parent directory (and
 * the whole path) is created as well.
 *
 * @return A {@link Path} of the created entry
 *
 * @throws IOException
 *     If anything bad happens
 */
public Path create() throws IOException {
    if (!path.toFile().exists()) {
        if (isDirectory) {
            return Files.createDirectories(path);
        } else {
            Files.createDirectories(path.getParent());
            return Files.createFile(path);
        }
    }
    return path;
}
 
开发者ID:arquillian,项目名称:smart-testing,代码行数:21,代码来源:LocalStorageAction.java

示例8: initialize

import java.nio.file.Files; //导入方法依赖的package包/类
@PostConstruct
public void initialize() {
  try {
    path = Paths.get("customers.json");
    if (!Files.exists(path)) {
      Files.createFile(path);
    }
    Files.write(path, "[]".getBytes());
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
开发者ID:openknowledge,项目名称:reactive-jax-rs,代码行数:13,代码来源:CustomerRepository.java

示例9: findWithFakeImageDirs

import java.nio.file.Files; //导入方法依赖的package包/类
private static DevDiskImages findWithFakeImageDirs(
    Predicate<Path> readablePredicate, String... imageDirNames) throws IOException {
  FileSystem fileSystem =
      Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("posix").build());
  Path rootImagesDir = fileSystem.getPath("path", "to", "images");
  Files.createDirectories(rootImagesDir);
  for (String imageDirName : imageDirNames) {
    Path imageDir = rootImagesDir.resolve(imageDirName);
    Files.createDirectory(imageDir);
    Files.createFile(imageDir.resolve("DiskImage." + DevDiskImages.IMAGE_EXTENSION));
    Files.createFile(imageDir.resolve("DiskImage." + DevDiskImages.SIGNATURE_EXTENSION));
  }
  return DevDiskImages.forTesting(rootImagesDir, readablePredicate);
}
 
开发者ID:google,项目名称:ios-device-control,代码行数:15,代码来源:DevDiskImagesTest.java

示例10: setUp

import java.nio.file.Files; //导入方法依赖的package包/类
@Before
public void setUp() throws Exception {
    fileSystem = Jimfs.newFileSystem(Configuration.unix());
    Files.createFile(fileSystem.getPath("/db"));
    Files.createFile(fileSystem.getPath("/db0"));
    Files.createFile(fileSystem.getPath("/db2"));
    platformConfig = new InMemoryPlatformConfig(fileSystem);
    MapModuleConfig moduleConfig = platformConfig.createModuleConfig("mapdb-app-file-system");
    moduleConfig.setStringProperty("drive-name", "db");
    moduleConfig.setStringProperty("remotely-accessible", "true");
    moduleConfig.setPathProperty("db-file", fileSystem.getPath("/db"));
    moduleConfig.setStringProperty("max-additional-drive-count", "1");
    moduleConfig.setStringProperty("drive-name-0", "db0");
    moduleConfig.setPathProperty("db-file-0", fileSystem.getPath("/db0"));
}
 
开发者ID:powsybl,项目名称:powsybl-core,代码行数:16,代码来源:MapDbAppFileSystemConfigTest.java

示例11: createInfra

import java.nio.file.Files; //导入方法依赖的package包/类
String createInfra() throws IOException {

		this.basePath = Files.createTempDirectory("java-build-pack");
		this.wdPath = Files.createTempDirectory(basePath, "di_ws_");
		this.workdir = Files.createTempDirectory(basePath, "workdir");
		Path launcher = Files.createFile(new File(basePath.toString() + "/Launcher.sh").toPath());
		// Return Log msg
		return String.format("TEST Env:\nBasePath=%s\nWorkdir=%s\nLauncher script=%s\n ",
				basePath.toString(), workdir.toString(), launcher.toString());
		
	}
 
开发者ID:SAP,项目名称:cloud-language-servers-container,代码行数:12,代码来源:LSPEndPointTestUtil.java

示例12: setSparseCheckout

import java.nio.file.Files; //导入方法依赖的package包/类
private void setSparseCheckout(File gitDir, Set<String> checkoutFiles) throws GitException {
    try (Git git = gitOpen()) {
        StoredConfig config = git.getRepository().getConfig();
        config.setBoolean("core", null, "sparseCheckout", true);
        config.save();

        Path sparseCheckoutPath = Paths.get(gitDir.getAbsolutePath(), "info", "sparse-checkout");
        try {
            Files.createDirectory(sparseCheckoutPath.getParent());
            Files.createFile(sparseCheckoutPath);
        } catch (FileAlreadyExistsException ignore) {
        }

        Charset charset = Charset.forName("UTF-8");

        // load all existing
        Set<String> exists = new HashSet<>();
        try (BufferedReader reader = Files.newBufferedReader(sparseCheckoutPath, charset)) {
            exists.add(reader.readLine());
        }

        // write
        try (BufferedWriter writer = Files.newBufferedWriter(sparseCheckoutPath, charset)) {
            if (!exists.isEmpty()) {
                writer.newLine();
            }

            for (String checkoutFile : checkoutFiles) {
                if (exists.contains(checkoutFile)) {
                    continue;
                }
                writer.write(checkoutFile);
                writer.newLine();
            }
        }

    } catch (Throwable e) {
        throw new GitException("Fail to set sparse checkout config", e);
    }
}
 
开发者ID:FlowCI,项目名称:flow-platform,代码行数:41,代码来源:JGitBasedClient.java

示例13: shouldRemoveFiles

import java.nio.file.Files; //导入方法依赖的package包/类
/**
 * Should remove files.
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@Test
public void shouldRemoveFiles() throws IOException {
	registry.add("jdbc.Statement.Duration", "select", 123);
	String line = "jdbc{host=\"localhost\",instance=\"Statement\",type=\"Duration\",type_instance=\"select\"} 123 1510373758000\n";
	Files.createFile(tempPath.resolve("1510373738123.prom"));
	Files.createFile(tempPath.resolve("1510373748123.prom"));
	Files.write(tempPath.resolve("1510373758123.prom"), line.getBytes(), StandardOpenOption.CREATE_NEW);
	boolean success = reporter.report();
	File[] promFiles = tempPath.toFile().listFiles((f, s) -> s.endsWith(".prom"));
	assertThat(success).isTrue();
	assertThat(promFiles.length).isEqualTo(2);
	assertThat(promFiles[0].getName()).isEqualTo("1510373748123.prom");
	assertThat(promFiles[1].getName()).isEqualTo("1510373758123.prom");
}
 
开发者ID:mevdschee,项目名称:tqdev-metrics,代码行数:21,代码来源:PrometheusLogReporterTest.java

示例14: testConfigContainsDir

import java.nio.file.Files; //导入方法依赖的package包/类
public void testConfigContainsDir() throws Exception {
    Tuple<Path, Environment> env = createEnv(fs, temp);
    Path pluginDir = createPluginDir(temp);
    Path dirInConfigDir = pluginDir.resolve("config").resolve("foo");
    Files.createDirectories(dirInConfigDir);
    Files.createFile(dirInConfigDir.resolve("myconfig.yml"));
    String pluginZip = createPlugin("fake", pluginDir);
    UserException e = expectThrows(UserException.class, () -> installPlugin(pluginZip, env.v1()));
    assertTrue(e.getMessage(), e.getMessage().contains("Directories not allowed in config dir for plugin"));
    assertInstallCleaned(env.v2());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:12,代码来源:InstallPluginCommandTests.java

示例15: testDirectoryStreamClosed

import java.nio.file.Files; //导入方法依赖的package包/类
void testDirectoryStreamClosed(String loc) throws IOException {
    System.err.println("testDirectoryStreamClosed(" + loc + ")");
    Path javaHome = prepareJavaHome();
    Path targetPath = javaHome.resolve(loc.replace("*", "/java.base").replace("/", sep));
    Path testClass = targetPath.resolve(("java/lang/" + TEST_FILE).replace("/", sep));
    Files.createDirectories(testClass.getParent());
    Files.createFile(testClass);
    System.setProperty("java.home", javaHome.toString());

    for (int i = 0; i < REPEATS; i++) {
        try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {
            Iterable<JavaFileObject> javaLangContent =
                    fm.list(StandardLocation.PLATFORM_CLASS_PATH,
                            "java.lang",
                            EnumSet.allOf(JavaFileObject.Kind.class),
                            false);
            boolean found = false;

            for (JavaFileObject fo : javaLangContent) {
                if (!fo.getName().endsWith(TEST_FILE)) {
                    throw new IllegalStateException("Wrong file: " + fo);
                }
                found = true;
            }

            if (!found)
                throw new IllegalStateException("Could not find the expected file!");
        }
    }

    System.err.println("finished.");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:33,代码来源:ExplodedImage.java


注:本文中的java.nio.file.Files.createFile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。