當前位置: 首頁>>代碼示例>>Java>>正文


Java Files.write方法代碼示例

本文整理匯總了Java中java.nio.file.Files.write方法的典型用法代碼示例。如果您正苦於以下問題:Java Files.write方法的具體用法?Java Files.write怎麽用?Java Files.write使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.file.Files的用法示例。


在下文中一共展示了Files.write方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: replaceFileLineStartsWith

import java.nio.file.Files; //導入方法依賴的package包/類
public static void replaceFileLineStartsWith(String oldLine, String newLine, String filePath) {
  Path path = Paths.get(filePath);
  List<String> fileContent;
  try {
    fileContent = new ArrayList<>(Files.readAllLines(path, StandardCharsets.UTF_8));
    for (int i = 0; i < fileContent.size(); i++) {
      if (fileContent.get(i).startsWith(oldLine)) {
        fileContent.set(i, newLine);
        break;
      }
    }
    Files.write(path, fileContent, StandardCharsets.UTF_8);
  } catch (IOException e) {
    e.printStackTrace();
  }
}
 
開發者ID:Svetroid,項目名稱:Hobbes-v1,代碼行數:17,代碼來源:FileUtils.java

示例2: realMain

import java.nio.file.Files; //導入方法依賴的package包/類
private static void realMain(String[] args) throws Throwable {
    test(false, new File(fileName));

    /* create the file and write its contents */
    File file = File.createTempFile(fileName, null);
    file.deleteOnExit();
    Files.write(file.toPath(), FILE_CONTENTS.getBytes());

    test(true, file);
    file.delete();
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:12,代碼來源:FailingConstructors.java

示例3: testReadAllBytesOnCustomFS

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Exercise Files.readAllBytes(Path) on custom file system. This is special
 * because readAllBytes was originally implemented to use FileChannel
 * and so may not be supported by custom file system providers.
 */
public void testReadAllBytesOnCustomFS() throws IOException {
    Path myfile = PassThroughFileSystem.create().getPath("myfile");
    try {
        int size = 0;
        while (size <= 1024) {
            byte[] b1 = genBytes(size);
            Files.write(myfile, b1);
            byte[] b2 = Files.readAllBytes(myfile);
            assertTrue(Arrays.equals(b1, b2), "bytes not equal");
            size += 512;
        }
    } finally {
        Files.deleteIfExists(myfile);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:BytesAndLines.java

示例4: testCreate

import java.nio.file.Files; //導入方法依賴的package包/類
@Test
public void testCreate() throws IOException {
  when(langDetection.language(any(InputFile.class))).thenReturn("java");

  Path path = temp.getRoot().toPath().resolve("file");
  Files.write(path, "test".getBytes(StandardCharsets.ISO_8859_1));
  ClientInputFile file = new TestClientInputFile(path, true, StandardCharsets.ISO_8859_1);

  InputFileBuilder builder = new InputFileBuilder(langDetection, metadata);
  SonarLintInputFile inputFile = builder.create(file);

  assertThat(inputFile.type()).isEqualTo(InputFile.Type.TEST);
  assertThat(inputFile.file()).isEqualTo(path.toFile());
  assertThat(inputFile.language()).isEqualTo("java");
  assertThat(inputFile.lines()).isEqualTo(1);

  assertThat(builder.langDetection()).isEqualTo(langDetection);
}
 
開發者ID:instalint-org,項目名稱:instalint,代碼行數:19,代碼來源:InputFileBuilderTest.java

示例5: testTrigger

import java.nio.file.Files; //導入方法依賴的package包/類
@Test()
public void testTrigger() throws Exception {
    final Path keyfile = Paths.get("./junit/etc/minebox/randomkey.txt");
    try {
        Assert.assertFalse(Files.exists(keyfile));
        final LazyEncyptionKeyProvider key = new LazyEncyptionKeyProvider("./junit/etc/minebox/randomkey.txt");
        final ListenableFuture<String> masterPassword = key.getMasterPassword();
        Assert.assertFalse(masterPassword.isDone());
        Files.write(keyfile, PWBYTES);
        Thread.sleep(1000);
        Assert.assertTrue(masterPassword.isDone());
        Assert.assertEquals(PW, key.getImmediatePassword());
    } finally {
        Files.delete(keyfile);
    }
}
 
開發者ID:MineboxOS,項目名稱:tools,代碼行數:17,代碼來源:EncyptionKeyProviderTest.java

示例6: writeNewFile

import java.nio.file.Files; //導入方法依賴的package包/類
public static void writeNewFile(String path, String fileName, byte[] content) throws IOException {
	File file = new File(path);
	if (!file.exists()) {
		if (!file.mkdirs()) {
			throw new IOException("make dir failed!");
		}
	} else {
		if (!file.isDirectory()) {
			return;
		}
	}
	File temp = new File(path + "//" + fileName);
	if (!temp.exists()) {
		if (!temp.createNewFile()) {
			throw new IOException("create new file failed!");
		}
	}
	Files.write(temp.toPath(), content);
}
 
開發者ID:HankXV,項目名稱:Limitart,代碼行數:20,代碼來源:FileUtil.java

示例7: openDialogueDLC

import java.nio.file.Files; //導入方法依賴的package包/類
private void openDialogueDLC() {
    FileChooser chooser = new FileChooser();
    File file = chooser.showOpenDialog(GuiData.getInstance().getStage());
    if (file != null) {
        try {
            File workingFile = File.createTempFile("FEFWORKING", null, FileData.getInstance().getTemp());
            FileData.getInstance().setWorkingFile(workingFile);
            byte[] out = Files.readAllBytes(Paths.get(file.getCanonicalPath()));
            Files.write(Paths.get(workingFile.getCanonicalPath()), out);

            FXMLLoader loader = new FXMLLoader(FEFEditor.class.getResource("gui/fxml/fates/DialogueDLC.fxml"));
            content = loader.load();
            changeContent();
            DialogueDLC controller = loader.getController();
            controller.addAccelerators();

            FileData.getInstance().getWorkingFile().deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
開發者ID:thane98,項目名稱:FEFEditor,代碼行數:23,代碼來源:Selection.java

示例8: saveModes

import java.nio.file.Files; //導入方法依賴的package包/類
public void saveModes(File file){
	ArrayList<String> lines = new ArrayList<String>();
	
	lines.add("<?xml version=\"1.0\" ?>");
	lines.add("<mode-selector>");
	for (int i = 0; i < modes.size(); i++) {
		lines.add("\t<mode name=\""+modes.get(i).name+"\" value=\""+modes.get(i).value+"\" />");
	}
	lines.add("</mode-selector>");
	
	try {
		Files.write(file.toPath(), lines, StandardOpenOption.CREATE);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
開發者ID:Flash3388,項目名稱:FlashLib,代碼行數:17,代碼來源:ModeSelectorControl.java

示例9: createUser

import java.nio.file.Files; //導入方法依賴的package包/類
public CreateUserResponse createUser(LoginRequest req){
	if(users.containsKey(req.getUserName())){
		req.setPassword("");
		return new CreateUserResponse(Constants.ALREADY_EXISTS,false, req);
	}else{
		users.put(req.getUserName(), req.getPassword());
		try {
			Files.write(Paths.get(Constants.DATA_FILE_PATH), req.getUserName().concat("=").concat(req.getPassword()).getBytes(), StandardOpenOption.APPEND);
		} catch (Exception e) {
			logger.error("Error",e);
		}
		req.setPassword("");
		return new CreateUserResponse(Constants.CREATED, true, req);
	}
}
 
開發者ID:zafar142007,項目名稱:FolderSync,代碼行數:16,代碼來源:AuthService.java

示例10: store

import java.nio.file.Files; //導入方法依賴的package包/類
@Override
public UserSessionFile store(String fileContent, String sessionId) {
    String filename = UUID.randomUUID() + ".mztab";
    try {
        Path sessionPath = buildSessionPath(sessionId);
        Files.createDirectories(sessionPath);
        Files.write(buildPathToFile(sessionPath, filename), fileContent.
            getBytes("UTF-8"), StandardOpenOption.CREATE,
            StandardOpenOption.WRITE);
        return new UserSessionFile(filename, sessionId);
    } catch (IOException e) {
        throw new StorageException("Failed to store file " + filename, e);
    }
}
 
開發者ID:nilshoffmann,項目名稱:jmzTab-m,代碼行數:15,代碼來源:FileSystemStorageService.java

示例11: replacePackageName

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Replace the package names from "com.fujitsu.bss.app" to "org.oscm.app" in
 * the existing log files.
 */
private void replacePackageName(String filePath) {
    try {
        Path path = Paths.get(filePath);
        Charset charset = StandardCharsets.UTF_8;
        String content = new String(Files.readAllBytes(path), charset);
        content = content.replaceAll("com.fujitsu.bss.app", "org.oscm.app");
        Files.write(path, content.getBytes(charset));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:servicecatalog,項目名稱:oscm-app,代碼行數:16,代碼來源:Initializer.java

示例12: saveData

import java.nio.file.Files; //導入方法依賴的package包/類
@Override
public boolean saveData(StoreImage data) {
	// We return true so we do not trigger an error. This is intended
	if (!dataIsStorable(data)) {
		return true;
	}
	
	Path imgFile = workingDir.resolve(Long.toString(data.getId()));
	if (imgFile.toFile().exists()) {
		return true;
	}
	
	ReadWriteLock l = getIDLock(data.getId());
	l.writeLock().lock();
	
	try {
		Files.write(imgFile, data.getByteArray(), 
				StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
	} catch (IOException ioException) {
		log.warn("An IOException occured while trying to write the file \"" + imgFile.toAbsolutePath() 
				+ "\" to disk.", ioException);
		return false;
	} finally {
		l.writeLock().unlock();
	}
	
	return true;
}
 
開發者ID:DescartesResearch,項目名稱:Pet-Supply-Store,代碼行數:29,代碼來源:DriveStorage.java

示例13: outputErrorLog

import java.nio.file.Files; //導入方法依賴的package包/類
private static void outputErrorLog(List<File> failures) {
    List<String> out = new ArrayList<>();
    out.add("The following files failed to verify: ");
    for(File f : failures)
        out.add(f.getAbsolutePath());
    try {
        Files.write(Paths.get(System.getProperty("user.dir") + "/VerificationFailures.txt"), out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:thane98,項目名稱:3DSFE-Randomizer,代碼行數:12,代碼來源:AVerifier.java

示例14: should_not_find_untracked_tests_as_changed

import java.nio.file.Files; //導入方法依賴的package包/類
@Test
public void should_not_find_untracked_tests_as_changed() throws IOException {
    //given
    Configuration configuration = createConfiguration("7699c2c", "04d04fe");
    final File testFile = gitFolder.newFile("core.src.test.java.org.arquillian.smart.testing.CalculatorTest.java");
    Files.write(testFile.toPath(), ("package org.arquillian.smart.testing;\n"
        + "\n"
        + "import org.junit.Assert;\n"
        + "import org.junit.Test;\n"
        + "\n"
        + "public class CalculatorTest {\n"
        + "\n"
        + "    @Test\n"
        + "    public void should_add_numbers() {\n"
        + "        Assert.assertEquals(6, 4 + 2);\n"
        + "    }\n"
        + "}").getBytes(), StandardOpenOption.APPEND);

    final ChangedTestsDetector changedTestsDetector =
        new ChangedTestsDetector(new GitChangeResolver(), new NoopStorage(), gitFolder.getRoot(),
            className -> className.endsWith("Test"), configuration);

    // when
    final Collection<TestSelection> changedTest = changedTestsDetector.getTests();

    // then
    assertThat(changedTest).extracting(TestSelection::getClassName)
        .containsOnly("org.arquillian.smart.testing.vcs.git.NewFilesDetectorTest")
        .doesNotContain("org.arquillian.smart.testing.CalculatorTest");
}
 
開發者ID:arquillian,項目名稱:smart-testing,代碼行數:31,代碼來源:ChangedTestsDetectorTest.java

示例15: getOrCreateCounterFile

import java.nio.file.Files; //導入方法依賴的package包/類
private File getOrCreateCounterFile(String fileName) {
    File f = new File(eventsDirectory + File.separator + fileName);
    if (!f.exists()) {
        try {
            logger.debug("File for name: " + fileName + "does not exist, creating");
            f.createNewFile();
            Files.write(f.toPath(), "0".getBytes(Charset.forName("UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return f;
}
 
開發者ID:larscheid-schmitzhermes,項目名稱:keycloak-monitoring-prometheus,代碼行數:14,代碼來源:MonitoringEventListenerProvider.java


注:本文中的java.nio.file.Files.write方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。