Java Code Examples for com.intellij.openapi.util.io.FileUtil#writeToFile()

The following examples show how to use com.intellij.openapi.util.io.FileUtil#writeToFile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDirectoryNonExisting() throws Exception {
  File topDir = createTestDir("top");
  File subDir = new File(topDir, "subDir");
  File file = new File(subDir, "file.txt");
  refresh(topDir);

  LocalFileSystem.WatchRequest request = watch(subDir);
  try {
    myAccept = true;
    assertTrue(subDir.toString(), subDir.mkdir());
    assertEvent(VFileCreateEvent.class, subDir.getPath());
    refresh(subDir);

    myAccept = true;
    FileUtil.writeToFile(file, "new content");
    assertEvent(VFileCreateEvent.class, file.getPath());
  }
  finally {
    unwatch(request);
    delete(topDir);
  }
}
 
Example 2
Source File: L2GitUtil.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
/**
 * Adds a new line of text to a file and adds/commits it
 *
 * @param file
 * @param repository
 * @param project
 * @throws IOException
 * @throws IOException
 */
public static void editAndCommitFile(final File file, final git4idea.repo.GitRepository repository, final Project project) throws IOException {
    // edits file
    final VirtualFile readmeVirtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
    Assert.assertNotNull("Git repository should have a " + file.getName() + " file", readmeVirtualFile);
    FileUtil.writeToFile(file, "\nnew line", true);

    // adds and commits the change
    final LocalChangeListImpl localChangeList = LocalChangeListImpl.createEmptyChangeListImpl(project, "TestCommit", "12345");
    final ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(project);
    VcsDirtyScopeManager.getInstance(project).markEverythingDirty();
    changeListManager.ensureUpToDate(false);
    changeListManager.addUnversionedFiles(localChangeList, ImmutableList.of(readmeVirtualFile));
    final Change change = changeListManager.getChange(LocalFileSystem.getInstance().findFileByIoFile(file));
    repository.getVcs().getCheckinEnvironment().commit(ImmutableList.of(change), COMMIT_MESSAGE);
}
 
Example 3
Source File: AssertEx.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void assertSameLinesWithFile(String filePath, String actualText) {
  String fileText;
  try {
    if (OVERWRITE_TESTDATA) {
      FileUtil.writeToFile(new File(filePath), actualText);
      System.out.println("File " + filePath + " created.");
    }
    fileText = FileUtil.loadFile(new File(filePath));
  }
  catch (IOException e) {
    throw new RuntimeException(e);
  }
  String expected = StringUtil.convertLineSeparators(fileText.trim());
  String actual = StringUtil.convertLineSeparators(actualText.trim());
  if (!Comparing.equal(expected, actual)) {
    throw new FileComparisonFailure(null, expected, actual, filePath);
  }
}
 
Example 4
Source File: RoutesManager.java    From railways with MIT License 6 votes vote down vote up
/**
 * Saves passed output string to cache file and sets the same modification time as routes.rb has.
 *
 * @param output String that contains stdout of 'rake routes' command.
 */
private void cacheOutput(String output) {
    try {
        String fileName = getCacheFileName();
        if (fileName == null)
            return;

        // Cache output
        File f = new File(fileName);
        FileUtil.writeToFile(f, output.getBytes(), false);

        // Set cache file modification date/time the same as for routes.rb
        f.setLastModified(getRoutesFilesMTime());
    } catch (Exception e) {
        // Do nothing
    }
}
 
Example 5
Source File: CachedProviderTest.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() throws Exception {
	FileUtil.writeToFile(tempFile, "foo");
	tempFile.setLastModified(1000);
	String s = cachedProvider.get();
	Assert.assertEquals("foo", s);

	FileUtil.writeToFile(tempFile, "bar");

	tempFile.setLastModified(1000);
	s = cachedProvider.get();
	Assert.assertEquals("foo", s);

	tempFile.setLastModified(2000);
	s = cachedProvider.get();
	Assert.assertEquals("bar", s);
}
 
Example 6
Source File: ProjectStoreImplIdeaDirTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected File getTempProjectDir() throws IOException {
  final File projectDir = FileUtil.createTempDirectory(getTestName(true), "project");
  File ideaDir = new File(projectDir, Project.DIRECTORY_STORE_FOLDER);
  assertTrue(ideaDir.mkdir() || ideaDir.isDirectory());
  File iprFile = new File(ideaDir, "misc.xml");
  FileUtil.writeToFile(iprFile, getIprFileContent());

  myFilesToDelete.add(projectDir);
  return projectDir;
}
 
Example 7
Source File: VfsTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public static void overwriteTestData(String filePath, String actual) {
  try {
    FileUtil.writeToFile(new File(filePath), actual);
  }
  catch (IOException e) {
    throw new AssertionError(e);
  }
}
 
Example 8
Source File: VMOptionsTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritingNew() throws IOException {
  FileUtil.writeToFile(myFile, "-someOption");

  VMOptions.writeOption(VMOptions.MemoryKind.HEAP, 1024);
  VMOptions.writeOption(VMOptions.MemoryKind.METASPACE, 256);
  VMOptions.writeOption(VMOptions.MemoryKind.CODE_CACHE, 256);

  assertThat(FileUtil.loadFile(myFile)).isEqualToIgnoringWhitespace("-someOption -Xmx1024m -XX:MaxMetaspaceSize=256m -XX:ReservedCodeCacheSize=256m");
}
 
Example 9
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testDirectoryRecursive() throws Exception {
  File topDir = createTestDir("top");
  refresh(topDir);

  LocalFileSystem.WatchRequest request = watch(topDir);
  try {
    myAccept = true;
    File subDir = createTestDir(topDir, "sub");
    assertEvent(VFileCreateEvent.class, subDir.getPath());
    refresh(subDir);

    myAccept = true;
    File file = createTestFile(subDir, "test.txt");
    assertEvent(VFileCreateEvent.class, file.getPath());

    myAccept = true;
    FileUtil.writeToFile(file, "new content");
    assertEvent(VFileContentChangeEvent.class, file.getPath());

    myAccept = true;
    FileUtil.delete(file);
    assertEvent(VFileDeleteEvent.class, file.getPath());

    myAccept = true;
    FileUtil.writeToFile(file, "re-creation");
    assertEvent(VFileCreateEvent.class, file.getPath());
  }
  finally {
    unwatch(request);
    delete(topDir);
  }
}
 
Example 10
Source File: VMOptions.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void writeGeneralOption(@Nonnull Pattern pattern, @Nonnull String value) {
  File file = getWriteFile();
  if (file == null) {
    LOG.warn("VM options file not configured");
    return;
  }

  try {
    String content = file.exists() ? FileUtil.loadFile(file) : read();

    if (!StringUtil.isEmptyOrSpaces(content)) {
      Matcher m = pattern.matcher(content);
      if (m.find()) {
        StringBuffer b = new StringBuffer();
        m.appendReplacement(b, Matcher.quoteReplacement(value));
        m.appendTail(b);
        content = b.toString();
      }
      else {
        content = StringUtil.trimTrailing(content) + SystemProperties.getLineSeparator() + value;
      }
    }
    else {
      content = value;
    }

    if (file.exists()) {
      FileUtil.setReadOnlyAttribute(file.getPath(), false);
    }
    else {
      FileUtil.ensureExists(file.getParentFile());
    }

    FileUtil.writeToFile(file, content);
  }
  catch (IOException e) {
    LOG.warn(e);
  }
}
 
Example 11
Source File: BaseApplication.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void createLocatorFile() {
  ContainerPathManager containerPathManager = ContainerPathManager.get();
  File locatorFile = new File(containerPathManager.getSystemPath() + "/" + ApplicationEx.LOCATOR_FILE_NAME);
  try {
    byte[] data = containerPathManager.getHomePath().getBytes(CharsetToolkit.UTF8_CHARSET);
    FileUtil.writeToFile(locatorFile, data);
  }
  catch (IOException e) {
    LOG.warn("can't store a location in '" + locatorFile + "'", e);
  }
}
 
Example 12
Source File: IJRCTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public void testIterateRcPickup() throws IOException {
  File temp = new File(getHomePath(), IJRC.ITERATE_RC_FILENAME);
  FileUtil.writeToFile(temp, "123");
  Optional<String> rc = IJRC.getIteratePantsRc(temp.getParent());
  assertTrue(rc.isPresent());
  assertEquals(String.format("--pantsrc-files=%s", temp.getPath()), rc.get());
  temp.delete();
}
 
Example 13
Source File: IJRCTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public void testRcPickup() throws IOException {
  File temp = new File(getHomePath(), IJRC.IMPORT_RC_FILENAME);
  FileUtil.writeToFile(temp, "123");
  Optional<String> rc = IJRC.getImportPantsRc(temp.getParent());
  assertTrue(rc.isPresent());
  assertEquals(String.format("--pantsrc-files=%s", temp.getPath()), rc.get());
  temp.delete();
}
 
Example 14
Source File: IntegrationTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected String createFileExternally(String name, String content) throws IOException {
  File f = new File(myRoot.getPath(), name);
  f.getParentFile().mkdirs();
  f.createNewFile();
  if (content != null) FileUtil.writeToFile(f, content.getBytes());
  return FileUtil.toSystemIndependentName(f.getPath());
}
 
Example 15
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testFileLength() throws Exception {
  File file = FileUtil.createTempFile("test", "txt");
  FileUtil.writeToFile(file, "hello");
  VirtualFile virtualFile = myFS.refreshAndFindFileByIoFile(file);
  assertNotNull(virtualFile);
  String s = VfsUtilCore.loadText(virtualFile);
  assertEquals("hello", s);
  assertEquals(5, virtualFile.getLength());

  FileUtil.writeToFile(file, "new content");
  ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents();
  s = VfsUtilCore.loadText(virtualFile);
  assertEquals("new content", s);
  assertEquals(11, virtualFile.getLength());
}
 
Example 16
Source File: ExternalStorageQueue.java    From consulo with Apache License 2.0 4 votes vote down vote up
private File writeLocalFile(@Nonnull File proxyDirectory, @Nonnull String fileSpec, RoamingType roamingType, byte[] compressedData) throws IOException {
  File file = new File(proxyDirectory, ExternalStorage.buildFileSpec(roamingType, fileSpec));
  FileUtil.createParentDirs(file);
  FileUtil.writeToFile(file, compressedData);
  return file;
}
 
Example 17
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void testSubst() throws Exception {
  if (!SystemInfo.isWindows) {
    System.err.println("Ignored: Windows required");
    return;
  }

  File targetDir = createTestDir("top");
  File subDir = createTestDir(targetDir, "sub");
  File file = createTestFile(subDir, "test.txt");
  File rootFile = createSubst(targetDir.getPath());
  VfsRootAccess.allowRootAccess(rootFile.getPath());
  VirtualFile vfsRoot = myFileSystem.findFileByIoFile(rootFile);

  try {
    assertNotNull(rootFile.getPath(), vfsRoot);
    File substDir = new File(rootFile, subDir.getName());
    File substFile = new File(substDir, file.getName());
    refresh(targetDir);
    refresh(substDir);
    myAcceptedDirectories.add(substDir.getPath());

    LocalFileSystem.WatchRequest request = watch(substDir);
    try {
      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, substFile.getPath());

      LocalFileSystem.WatchRequest request2 = watch(targetDir);
      try {
        myAccept = true;
        FileUtil.delete(file);
        assertEvent(VFileDeleteEvent.class, file.getPath(), substFile.getPath());
      }
      finally {
        unwatch(request2);
      }

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, substFile.getPath());
    }
    finally {
      unwatch(request);
    }
  }
  finally {
    delete(targetDir);
    deleteSubst(rootFile.getPath());
    if (vfsRoot != null) {
      ((NewVirtualFile)vfsRoot).markDirty();
      myFileSystem.refresh(false);
    }
    VfsRootAccess.disallowRootAccess(rootFile.getPath());
  }
}
 
Example 18
Source File: ExternalDiffToolUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static File createFile(@Nonnull byte[] bytes, @Nonnull FileNameInfo fileName) throws IOException {
  File tempFile = FileUtil.createTempFile(fileName.prefix + "_", "_" + fileName.name, true);
  FileUtil.writeToFile(tempFile, bytes);
  return tempFile;
}
 
Example 19
Source File: GitImportTest.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
@Test(timeout = 60000)
public void testImport_VSO() throws Exception {
    Debug.println("Start", null);
    final ImportModel importModel = new ImportModel(myProject, null, null, false);
    final String repoName = generateUniqueName("testRepo");

    final File projectPath = new File(myProjectPath);

    // Add a file to the folder
    final String uniqueString = UUID.randomUUID().toString();
    Debug.println("uniqueString", uniqueString);
    final File readme = new File(projectPath, README_FILE);
    FileUtil.writeToFile(readme, uniqueString);
    Debug.println("readme path", readme.getAbsolutePath());

    // Mock the select files dialog that the model calls into
    mockSelectFilesDialog(Collections.singletonList(readme));

    // Get the model and set fields appropriately
    VsoImportPageModel model = (VsoImportPageModel) importModel.getVsoImportPageModel();
    // To avoid the test loading all the accounts for the user, we set the account server we care about
    model.setServerName(getServerUrl());
    model.setUserName(getUser());
    model.setRepositoryName(repoName);

    // Load the projects and choose the right one
    model.loadTeamProjects();
    while (model.isAuthenticating() || model.isLoading()) {
        Thread.sleep(100);
    }

    // Now we need to find ours and select it
    ServerContext selectedContext = null;
    final ServerContextTableModel table = model.getTableModel();
    int index = -1;
    for (int i = 0; i < table.getRowCount(); i++) {
        final ServerContext context = table.getServerContext(i);
        if (context.getTeamProjectReference().getName().equalsIgnoreCase(getTeamProject())) {
            index = i;
            selectedContext = context;
            break;
        }
    }

    // verify that we found it
    Assert.assertTrue(index >= 0);
    // select it
    model.getTableSelectionModel().setSelectionInterval(index, index);

    // delete the repo if it already exists
    removeServerGitRepository(selectedContext, repoName);

    // clone it
    model.importIntoRepository();

    // verify that it got imported
    final GitRepository repo = getServerGitRepository(selectedContext, repoName);
    Assert.assertNotNull(repo);
    final GitHttpClient gitClient = selectedContext.getGitHttpClient();
    final InputStream contentStream = gitClient.getItemContent(repo.getId(), README_FILE, null);
    final BufferedReader bufferedContent = new BufferedReader(new InputStreamReader(contentStream));
    final String content = bufferedContent.readLine();
    Assert.assertEquals(uniqueString, content);
    bufferedContent.close();
    contentStream.close();
    selectedContext.dispose();
}
 
Example 20
Source File: Executor.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void overwrite(@Nonnull File file, @Nonnull String content) throws IOException {
  FileUtil.writeToFile(file, content.getBytes(), false);
}