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

The following are Jave code examples for showing how to use createFile() 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.
Example 1
Project: maven-archetype-springboot   File: CsvUtils.java   Source Code and License Vote up 6 votes
/**
 * 将数据库的数据导出为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);
    }
}
 
Example 2
Project: ClassViewer   File: RecentFiles.java   Source Code and License Vote up 6 votes
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);
    }
}
 
Example 3
Project: goobi-viewer-indexer   File: MetsIndexerTest.java   Source Code and License Vote up 6 votes
/**
 * @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));
}
 
Example 4
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License Vote up 5 votes
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());
}
 
Example 5
Project: openjdk-jdk10   File: JLinkNegativeTest.java   Source Code and License Vote up 5 votes
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|.)*");
}
 
Example 6
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License Vote up 5 votes
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());
}
 
Example 7
Project: smart-testing   File: LocalStorageAction.java   Source Code and License Vote up 5 votes
/**
 * 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;
}
 
Example 8
Project: reactive-jax-rs   File: CustomerRepository.java   Source Code and License Vote up 5 votes
@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();
  }
}
 
Example 9
Project: ios-device-control   File: DevDiskImagesTest.java   Source Code and License Vote up 5 votes
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);
}
 
Example 10
Project: powsybl-core   File: MapDbAppFileSystemConfigTest.java   Source Code and License Vote up 5 votes
@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"));
}
 
Example 11
Project: cloud-language-servers-container   File: LSPEndPointTestUtil.java   Source Code and License Vote up 5 votes
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());
		
	}
 
Example 12
Project: flow-platform   File: JGitBasedClient.java   Source Code and License Vote up 5 votes
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);
    }
}
 
Example 13
Project: tqdev-metrics   File: PrometheusLogReporterTest.java   Source Code and License Vote up 5 votes
/**
 * 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");
}
 
Example 14
Project: elasticsearch_my   File: InstallPluginCommandTests.java   Source Code and License Vote up 5 votes
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());
}
 
Example 15
Project: openjdk-jdk10   File: ExplodedImage.java   Source Code and License Vote up 5 votes
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.");
}
 
Example 16
Project: openjdk-jdk10   File: ValidateModulesTest.java   Source Code and License Vote up 4 votes
/**
 * Creates a file relative the given directory.
 */
private void touch(Path dir, String relPath) throws IOException {
    Path file = dir.resolve(relPath.replace('/', File.separatorChar));
    Files.createDirectories(file.getParent());
    Files.createFile(file);
}
 
Example 17
Project: lazythreetenbp   File: CompilerOptionsTest.java   Source Code and License Vote up 4 votes
@Test
public void leapSecondFile() throws Exception {
    Files.createFile(options.srcDir.resolve(options.leapSecondFileName));
    assertThat(options.leapSecondFile()).isNotNull();
}
 
Example 18
Project: powsybl-core   File: MapDbAppFileSystemProviderTest.java   Source Code and License Vote up 4 votes
@Before
public void setUp() throws Exception {
    fileSystem = Jimfs.newFileSystem(Configuration.unix());
    dbFile = fileSystem.getPath("/db");
    Files.createFile(dbFile);
}
 
Example 19
Project: openjdk-systemtest   File: PathDirectoryStreamTest.java   Source Code and License Vote up 4 votes
public static List<Path> staticCreateFiles(Path directory, int number) throws IOException {
	if (directory == null) {
		throw new NullPointerException("Path passed to createFiles cannot be null");
	}
	
	FileAttribute<?>[] attrs = {};	
	Files.createDirectories(directory, attrs);
	assertTrue("Directory was not created", Files.exists(directory));	
	List<Path> files = new LinkedList<Path>();
	
	for (int counter = 0 ; counter < number ; counter++) {		
		Path newFile = directory.resolve("file" + counter + ".txt");
		Files.createFile(newFile, attrs);
		assertTrue("File was not created", Files.exists(newFile));
		files.add(newFile);		
	}

	if(!ReiserSpotter.getIsReiser()){
		assertEquals("The number of files generated was not equal to the requested number", number, files.size());
	}
	
	// Check via another means
	final List<Path> visitorFiles = new LinkedList<Path>();
	
	if(!ReiserSpotter.getIsReiser()){	
		Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
			@Override
			public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
				if (path.toString().endsWith(".txt")) {
					visitorFiles.add(path);
				}
				return FileVisitResult.CONTINUE;
			}
		});
		
		assertEquals("DirectoryTools.createFiles() - The number of files created was not equal to the number seen using the FileVisitor. " +
				"FileVisitor found " + Arrays.toString(visitorFiles.toArray()) + " & we created " + Arrays.toString(files.toArray()) ,
				number, visitorFiles.size());
	}
	return files;	
}
 
Example 20
Project: googles-monorepo-demo   File: MoreFilesTest.java   Source Code and License Vote up 4 votes
/**
 * Creates a new file system for testing that supports the given features in addition to
 * supporting symbolic links. The file system is created initially having the following file
 * structure:
 *
 * <pre>
 *   /
 *      work/
 *         dir/
 *            a
 *            b/
 *               g
 *               h -> ../a
 *               i/
 *                  j/
 *                     k
 *                     l/
 *            c
 *            d -> b/i
 *            e/
 *            f -> /dontdelete
 *      dontdelete/
 *         a
 *         b/
 *         c
 *      symlinktodir -> work/dir
 * </pre>
 */
static FileSystem newTestFileSystem(Feature... supportedFeatures) throws IOException {
  FileSystem fs = Jimfs.newFileSystem(Configuration.unix().toBuilder()
      .setSupportedFeatures(ObjectArrays.concat(SYMBOLIC_LINKS, supportedFeatures))
      .build());
  Files.createDirectories(fs.getPath("dir/b/i/j/l"));
  Files.createFile(fs.getPath("dir/a"));
  Files.createFile(fs.getPath("dir/c"));
  Files.createSymbolicLink(fs.getPath("dir/d"), fs.getPath("b/i"));
  Files.createDirectory(fs.getPath("dir/e"));
  Files.createSymbolicLink(fs.getPath("dir/f"), fs.getPath("/dontdelete"));
  Files.createFile(fs.getPath("dir/b/g"));
  Files.createSymbolicLink(fs.getPath("dir/b/h"), fs.getPath("../a"));
  Files.createFile(fs.getPath("dir/b/i/j/k"));
  Files.createDirectory(fs.getPath("/dontdelete"));
  Files.createFile(fs.getPath("/dontdelete/a"));
  Files.createDirectory(fs.getPath("/dontdelete/b"));
  Files.createFile(fs.getPath("/dontdelete/c"));
  Files.createSymbolicLink(fs.getPath("/symlinktodir"), fs.getPath("work/dir"));
  return fs;
}