Java Code Examples for com.intellij.openapi.vfs.VirtualFile#contentsToByteArray()
The following examples show how to use
com.intellij.openapi.vfs.VirtualFile#contentsToByteArray() .
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: MuleSchemaProvider.java From mule-intellij-plugins with Apache License 2.0 | 6 votes |
private Map<String, String> getSchemasFromSpringSchemas(@NotNull Module module) throws Exception { Map<String, String> schemasMap = new HashMap<>(); PsiFile[] psiFiles = FilenameIndex.getFilesByName(module.getProject(), "spring.schemas", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module)); for (PsiFile nextSpringS : psiFiles) { VirtualFile springSchemasFile = nextSpringS.getVirtualFile(); if (springSchemasFile != null) { String springSchemasContent = new String(springSchemasFile.contentsToByteArray()); schemasMap.putAll(parseSpringSchemas(springSchemasContent)); } } //Fix for HTTP module schema vs old HTTP transport schema schemasMap.put("http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd", "META-INF/mule-httpn.xsd"); return schemasMap; }
Example 2
Source File: OpenSampleAction.java From mule-intellij-plugins with Apache License 2.0 | 6 votes |
@Override public void actionPerformed(AnActionEvent anActionEvent) { logger.debug("Loading sample!"); final Project project = anActionEvent.getProject(); final PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE); VirtualFile sample = FileChooser.chooseFile(FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(), project, null); if (sample == null) return; try { final String text = new String(sample.contentsToByteArray(), sample.getCharset()); new WriteCommandAction.Simple(project, psiFile) { @Override protected void run() throws Throwable { document.setText(text); } }.execute(); } catch (Exception e) { logger.error(e); } }
Example 3
Source File: LocalFilesystemModificationHandler.java From saros with GNU General Public License v2.0 | 6 votes |
/** * Returns the content of the given file. If available, the cached document content representing * the file held by Intellij will be used. Otherwise, the file content on disk (obtained using the * <code>VirtualFile</code>) will be used. * * @param file the file to get the content for * @return the content for the given file (cached by Intellij or read from disk if no cache is * available) or an empty byte array if the content of the file could not be obtained. * @see Document * @see VirtualFile */ private byte[] getContent(VirtualFile file) { Document document = DocumentAPI.getDocument(file); try { if (document != null) { return document.getText().getBytes(file.getCharset().name()); } else { log.debug( "Could not get Document for file " + file + ", using file content on disk instead. This content might" + " not correctly represent the current state of the file" + " in Intellij."); return file.contentsToByteArray(); } } catch (IOException e) { log.warn("Could not get content for file " + file, e); return new byte[0]; } }
Example 4
Source File: FlutterSdkUtil.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Parse any .packages file and infer the location of the Flutter SDK from that. */ @Nullable public static String guessFlutterSdkFromPackagesFile(@NotNull Module module) { for (PubRoot pubRoot : PubRoots.forModule(module)) { final VirtualFile packagesFile = pubRoot.getPackagesFile(); if (packagesFile == null) { continue; } // parse it try { final String contents = new String(packagesFile.contentsToByteArray(true /* cache contents */)); return parseFlutterSdkPath(contents); } catch (IOException ignored) { } } return null; }
Example 5
Source File: FlutterSdkVersion.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static String readVersionString(VirtualFile file) { try { final String data = new String(file.contentsToByteArray(), StandardCharsets.UTF_8); for (String line : data.split("\n")) { line = line.trim(); if (line.isEmpty() || line.startsWith("#")) { continue; } return line; } return null; } catch (IOException e) { return null; } }
Example 6
Source File: HaxeSymbolContributorTest.java From intellij-haxe with Apache License 2.0 | 6 votes |
protected void doTest(String... extraFiles) throws Throwable { final List<String> files = new ArrayList<String>(); files.add(getTestName(false) + ".hx"); Collections.addAll(files, extraFiles); myFixture.configureByFiles(files.toArray(new String[0])); final VirtualFile virtualFile = myFixture.copyFileToProject(getTestName(false) + ".txt"); String text = new String(virtualFile.contentsToByteArray()); List<String> includeLines = new ArrayList<String>(); for (String line : text.split("\n")) { line = line.trim(); if(line.length() > 0) { includeLines.add(line); } } checkSymbols(includeLines); }
Example 7
Source File: CustomIconLoader.java From intellij-extra-icons-plugin with MIT License | 6 votes |
public static ImageWrapper loadFromVirtualFile(VirtualFile virtualFile) throws IllegalArgumentException { if (virtualFile.getExtension() != null) { Image image; IconType iconType; byte[] fileContents; try { fileContents = virtualFile.contentsToByteArray(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileContents); if (virtualFile.getExtension().equals("svg") && new String(fileContents).startsWith("<")) { iconType = IconType.SVG; image = SVGLoader.load(byteArrayInputStream, 1.0f); } else { iconType = IconType.IMG; image = ImageLoader.loadFromStream(byteArrayInputStream); } } catch (IOException ex) { throw new IllegalArgumentException("IOException while trying to load image."); } if (image == null) { throw new IllegalArgumentException("Could not load image properly."); } return new ImageWrapper(iconType, scaleImage(image), fileContents); } return null; }
Example 8
Source File: TargetFileResolutionIntegrationTest.java From intellij-pants-plugin with Apache License 2.0 | 6 votes |
public void testAvailableTargetTypes() throws IOException { String helloProjectPath = "examples/src/scala/org/pantsbuild/example/hello/"; doImport(helloProjectPath); // should be only tested with pants versions above 1.24.0 if (PantsUtil.isCompatibleProjectPantsVersion(myProjectRoot.getPath(), "1.24.0")) { VirtualFile vfile = myProjectRoot.findFileByRelativePath(helloProjectPath + "BUILD"); assertNotNull(vfile); String input = new String(vfile.contentsToByteArray()); PsiFile build = PsiManager.getInstance(myProject).findFile(vfile); final PsiReference reference = build.findReferenceAt(input.indexOf("target(") + 1); assertNotNull("no reference", reference); final Collection<PsiElement> elements = TargetElementUtil.getInstance().getTargetCandidates(reference); assertNotNull(elements); assertEquals(1, elements.size()); } }
Example 9
Source File: LoadTextUtil.java From consulo with Apache License 2.0 | 6 votes |
/** * Loads content of given virtual file. If limit is {@value UNLIMITED} then full CharSequence will be returned. Else CharSequence * will be truncated by limit if it has bigger length. * * @param file Virtual file for content loading * @param limit Maximum characters count or {@value UNLIMITED} * @return Full or truncated CharSequence with file content * @throws IllegalArgumentException for binary files */ @Nonnull public static CharSequence loadText(@Nonnull final VirtualFile file, int limit) { FileType type = file.getFileType(); if (type.isBinary()) throw new IllegalArgumentException("Attempt to load truncated text for binary file: " + file.getPresentableUrl() + ". File type: " + type.getName()); if (file instanceof LightVirtualFile) { return limitCharSequence(((LightVirtualFile)file).getContent(), limit); } if (file.isDirectory()) { throw new AssertionError("'" + file.getPresentableUrl() + "' is a directory"); } try { byte[] bytes = limit == UNLIMITED ? file.contentsToByteArray() : FileUtil.loadFirstAndClose(file.getInputStream(), limit); return getTextByBinaryPresentation(bytes, file); } catch (IOException e) { return ArrayUtil.EMPTY_CHAR_SEQUENCE; } }
Example 10
Source File: TestFileSystem.java From intellij with Apache License 2.0 | 5 votes |
/** * Read lines from VirtualFile instances. The real File may not be created on disk (like on * testFileSystems), so we cannot use Files#readAllLines here. */ @Override public List<String> readAllLines(File file) throws IOException { VirtualFile vf = getVirtualFile(file); String text = new String(vf.contentsToByteArray(), UTF_8); if (text.length() == 0) { return ImmutableList.of(); } return Splitter.on("\n").splitToList(text); }
Example 11
Source File: ParsingUtils.java From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static GrammarRootAST parseGrammar(Project project, Tool antlr, VirtualFile grammarFile) { try { Document document = FileDocumentManager.getInstance().getDocument(grammarFile); String grammarText = document != null ? document.getText() : new String(grammarFile.contentsToByteArray()); ANTLRStringStream in = new ANTLRStringStream(grammarText); in.name = grammarFile.getPath(); return antlr.parse(grammarFile.getPath(), in); } catch (IOException ioe) { antlr.errMgr.toolError(ErrorType.CANNOT_OPEN_FILE, ioe, grammarFile); } return null; }
Example 12
Source File: DiffRequestFactoryImpl.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull @Override public MergeRequest createBinaryMergeRequest(@Nullable Project project, @Nonnull VirtualFile output, @Nonnull List<byte[]> byteContents, @Nullable String title, @Nonnull List<String> contentTitles, @Nullable Consumer<MergeResult> applyCallback) throws InvalidDiffRequestException { if (byteContents.size() != 3) throw new IllegalArgumentException(); if (contentTitles.size() != 3) throw new IllegalArgumentException(); try { FileContent outputContent = myContentFactory.createFile(project, output); if (outputContent == null) throw new InvalidDiffRequestException("Can't process file: " + output); byte[] originalContent = output.contentsToByteArray(); List<DiffContent> contents = new ArrayList<>(3); for (byte[] bytes : byteContents) { contents.add(myContentFactory.createFromBytes(project, bytes, output)); } return new BinaryMergeRequestImpl(project, outputContent, originalContent, contents, byteContents, title, contentTitles, applyCallback); } catch (IOException e) { throw new InvalidDiffRequestException("Can't read from file", e); } }
Example 13
Source File: HaxeCompletionTestBase.java From intellij-haxe with Apache License 2.0 | 5 votes |
protected void doTestInclude(String... extraFiles) throws Throwable { final List<String> files = new ArrayList<String>(); files.add(getTestName(false) + ".hx"); Collections.addAll(files, extraFiles); myFixture.configureByFiles(files.toArray(new String[0])); final VirtualFile virtualFile = myFixture.copyFileToProject(getTestName(false) + ".txt"); String text = new String(virtualFile.contentsToByteArray()); List<String> includeLines = new ArrayList<String>(); List<String> excludeLines = new ArrayList<String>(); boolean include = true; for (String line : text.split("\n")) { line = line.trim(); if (line.equals(":INCLUDE")) { include = true; } else if (line.equals(":EXCLUDE")) { include = false; } else if (line.length() == 0) { } else { if (include) { includeLines.add(line); } else { excludeLines.add(line); } } //System.out.println(line); } //System.out.println(text); myFixture.complete(CompletionType.BASIC, 1); checkCompletion(CheckType.INCLUDES, includeLines); checkCompletion(CheckType.EXCLUDES, excludeLines); }
Example 14
Source File: FileContentImpl.java From consulo with Apache License 2.0 | 5 votes |
@TestOnly public static FileContent createByFile(@Nonnull VirtualFile file) { try { return new FileContentImpl(file, file.contentsToByteArray()); } catch (IOException e) { throw new RuntimeException(e); } }
Example 15
Source File: VirtualFileImpl.java From consulo with Apache License 2.0 | 5 votes |
@Override @Nonnull public byte[] contentsToByteArray() throws IOException { if (myFileInfo == null) { throw new UnsupportedOperationException(); } VirtualFile localFile = myFileInfo.getLocalFile(); if (localFile != null) { return localFile.contentsToByteArray(); } return ArrayUtil.EMPTY_BYTE_ARRAY; }
Example 16
Source File: CurrentBinaryContentRevision.java From consulo with Apache License 2.0 | 5 votes |
@javax.annotation.Nullable public byte[] getBinaryContent() throws VcsException { final VirtualFile vFile = getVirtualFile(); if (vFile == null) return null; try { return vFile.contentsToByteArray(); } catch (IOException e) { throw new VcsException(e); } }
Example 17
Source File: MergeVersion.java From consulo with Apache License 2.0 | 4 votes |
@Override public byte[] getBytes() throws IOException { VirtualFile file = getFile(); if (file != null) return file.contentsToByteArray(); return myDocument.getText().getBytes(); }
Example 18
Source File: UnifiedModuleImpl.java From aem-ide-tooling-4-intellij with Apache License 2.0 | 4 votes |
@Override public String getSymbolicName() { // This is a verify central function as the Symbolic Name is the key to find the // bundle on the target server. // // - If this is a Maven Plugin then we check the maven-bundle-plugin and // check if hte Symbolic Name is set there and use this one // - Otherwise Check if there is a Symbolic Name specified in the Sling // Facet // - Otherwise check if a Manifest.mf can be found and look for the 'Bundle-SymbolicName' // - Otherwise take the groupId.artifactId String answer = null; if(mavenProject != null) { // Check if there is an Maven Bundle Plugin with an Symbolic Name override List<MavenPlugin> mavenPlugins = mavenProject.getPlugins(); for(MavenPlugin mavenPlugin : mavenPlugins) { if(FELIX_GROUP_ID.equals(mavenPlugin.getGroupId()) && BUNDLE_PLUGIN_ARTIFACT_ID.equals(mavenPlugin.getArtifactId())) { Element configuration = mavenPlugin.getConfigurationElement(); if(configuration != null) { Element instructions = configuration.getChild(INSTRUCTIONS_SECTION); if(instructions != null) { Element bundleSymbolicName = instructions.getChild(BUNDLE_SYMBOLIC_NAME_FIELD); if(bundleSymbolicName != null) { answer = bundleSymbolicName.getValue(); answer = answer != null && answer.trim().isEmpty() ? null : answer.trim(); } } } } } } if(answer == null && slingConfiguration != null) { answer = slingConfiguration.getOsgiSymbolicName(); } if(answer == null) { VirtualFile baseDir = module.getProject().getBaseDir(); VirtualFile buildDir = baseDir.getFileSystem().findFileByPath(getBuildDirectoryPath()); if(buildDir != null) { // Find a Metainf.mf file VirtualFile manifest = Util.findFileOrFolder(buildDir, MANIFEST_MF_FILE_NAME, false); if(manifest != null) { try { String content = new String(manifest.contentsToByteArray()); int index = content.indexOf(BUNDLE_SYMBOLIC_NAME_FIELD); if(index >= 0) { int index2 = content.indexOf("\n", index); if(index2 >= 0) { answer = content.substring(index + BUNDLE_SYMBOLIC_NAME_FIELD.length() + 2, index2); answer = answer.trim().isEmpty() ? null : answer.trim(); } } } catch(IOException e) { //AS TODO: Report the issues e.printStackTrace(); } } } } if(answer == null && mavenProject != null) { answer = mavenProject.getMavenId().getGroupId() + "." + mavenProject.getMavenId().getArtifactId(); } return answer == null ? NO_OSGI_BUNDLE : answer; }
Example 19
Source File: FlutterUtils.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 4 votes |
private static Map<String, Object> readPubspecFileToMap(@NotNull final VirtualFile pubspec) throws IOException { final String contents = new String(pubspec.contentsToByteArray(true /* cache contents */)); return loadPubspecInfo(contents); }
Example 20
Source File: LayoutDirAction.java From StringKiller with Apache License 2.0 | 4 votes |
@Override public void actionPerformed(AnActionEvent e) { VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE); if (file == null) { showError("找不到目标文件"); return; } if (!file.isDirectory()) { showError("请选择layout文件夹"); return; } else if (!file.getName().startsWith("layout")) { showError("请选择layout文件夹"); return; } VirtualFile[] children = file.getChildren(); StringBuilder sb = new StringBuilder(); for (VirtualFile child : children) { layoutChild(child, sb); } VirtualFile resDir = file.getParent(); if (resDir.getName().equalsIgnoreCase("res")) { VirtualFile[] chids = resDir.getChildren(); for (VirtualFile chid : chids) { if (chid.getName().startsWith("values")) { if (chid.isDirectory()) { VirtualFile[] values = chid.getChildren(); for (VirtualFile value : values) { if (value.getName().startsWith("strings")) { try { String content = new String(value.contentsToByteArray(), "utf-8"); System.out.println("utf-8=" + content); String result = content.replace("</resources>", sb.toString() + "\n</resources>"); FileUtils.replaceContentToFile(value.getPath(), result); } catch (IOException e1) { e1.printStackTrace(); } } } } } } } e.getActionManager().getAction(IdeActions.ACTION_SYNCHRONIZE).actionPerformed(e); }