/** * It can be necessary to determine which is the root of a path. For example, the root of * D:\Projects\Java is D:\. * * @param path The path used to get a root * @return The root which contais the specified path */ public static String getRoot(String path) { File file = new File(path); File[] roots = file.listRoots(); for (int i = 0; i < roots.length; i++) if (path.startsWith(roots[i].getPath())) return roots[i].getPath(); return path; }
public String saveAsFile(boolean accessingAsFile) throws IOException { File file = new SikuliIDEFileChooser(SikuliIDE.getInstance(), accessingAsFile).save(); if (file == null) { return null; } String bundlePath = FileManager.slashify(file.getAbsolutePath(), false); if (!file.getAbsolutePath().endsWith(".sikuli")) { bundlePath += ".sikuli"; } if (FileManager.exists(bundlePath)) { int res = JOptionPane.showConfirmDialog( null, SikuliIDEI18N._I("msgFileExists", bundlePath), SikuliIDEI18N._I("dlgFileExists"), JOptionPane.YES_NO_OPTION); if (res != JOptionPane.YES_OPTION) { return null; } } else { FileManager.mkdir(bundlePath); } try { saveAsBundle(bundlePath, (SikuliIDE.getInstance().getCurrentFileTabTitle())); if (Settings.isMac()) { if (!Settings.handlesMacBundles) { makeBundle(bundlePath, accessingAsFile); } } } catch (IOException iOException) { } return getCurrentShortFilename(); }
private String getCurrentShortFilename() { if (_srcBundlePath != null) { File f = new File(_srcBundlePath); return f.getName(); } return "Untitled"; }
@Override public boolean importData(JComponent comp, Transferable t) { DataFlavor htmlFlavor = DataFlavor.stringFlavor; if (canImport(comp, t.getTransferDataFlavors())) { try { String transferString = (String) t.getTransferData(htmlFlavor); EditorPane targetTextPane = (EditorPane) comp; for (Map.Entry<String, String> entry : _copiedImgs.entrySet()) { String imgName = entry.getKey(); String imgPath = entry.getValue(); File destFile = targetTextPane.copyFileToBundle(imgPath); String newName = destFile.getName(); if (!newName.equals(imgName)) { String ptnImgName = "\"" + imgName + "\""; newName = "\"" + newName + "\""; transferString = transferString.replaceAll(ptnImgName, newName); Debug.info(ptnImgName + " exists. Rename it to " + newName); } } targetTextPane.insertString(transferString); } catch (Exception e) { Debug.error(me + "importData: Problem pasting text\n%s", e.getMessage()); } return true; } return false; }
public void loadFile(String filename) { filename = FileManager.slashify(filename, false); setSrcBundle(filename + "/"); File script = new File(filename); _editingFile = FileManager.getScriptFile(script, null, null); if (_editingFile != null) { editingType = _editingFile .getAbsolutePath() .substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1); initBeforeLoad(editingType); try { this.read( new BufferedReader(new InputStreamReader(new FileInputStream(_editingFile), "UTF8")), null); } catch (Exception ex) { _editingFile = null; } } if (_editingFile != null) { updateDocumentListeners(); setDirty(false); _srcBundleTemp = false; } else { _srcBundlePath = null; } }
private void ListSubDirectorySizes(File file) { File[] files; files = file.listFiles( new FileFilter() { @Override public boolean accept(File file) { // if (!file.isDirectory()){ // return false; //To change body of implemented methods use // File | Settings | File Templates. // }else{ // return true; // } return true; } }); Map<String, Long> dirListing = new HashMap<String, Long>(); for (File dir : files) { DiskUsage diskUsage = new DiskUsage(); diskUsage.accept(dir); // long size = diskUsage.getSize() / (1024 * 1024); long size = diskUsage.getSize(); dirListing.put(dir.getName(), size); } ValueComparator bvc = new ValueComparator(dirListing); TreeMap<String, Long> sorted_map = new TreeMap<String, Long>(bvc); sorted_map.putAll(dirListing); PrettyPrint(file, sorted_map); }
public void secureDelete() { int rw = tblItems.getSelectedRow(); if (rw == -1) { JOptionPane.showMessageDialog(frm, "No item selected", "Error", JOptionPane.ERROR_MESSAGE); return; } int idx = tblItems.convertRowIndexToModel(rw); if (JOptionPane.showConfirmDialog( frm, "Delete " + store.plainName(idx) + "?", "Confirm Delete", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; File del = store.delete(idx); store.fireTableDataChanged(); if (del != null) { if (del.delete()) { // successful needsSave = true; } else { System.err.println("Delete " + del.getAbsolutePath() + " failed"); } } updateStatus(); }
// public static final String showElementTreeAction = "showElementTree"; // ------------------------------------------------------------- public void openFile(String currDirStr, String currFileStr) { if (fileDialog == null) { fileDialog = new FileDialog(this); } fileDialog.setMode(FileDialog.LOAD); if (!(currDirStr.equals(""))) { fileDialog.setDirectory(currDirStr); } if (!(currFileStr.equals(""))) { fileDialog.setFile(currFileStr); } fileDialog.show(); String file = fileDialog.getFile(); // cancel pushed if (file == null) { return; } String directory = fileDialog.getDirectory(); File f = new File(directory, file); if (f.exists()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) // oldDoc.removeUndoableEditListener(undoHandler); /* if (elementTreePanel != null) { elementTreePanel.setEditor(null); } */ getEditor().setDocument(new PlainDocument()); fileDialog.setTitle(file); Thread loader = new FileLoader(f, editor1.getDocument()); loader.start(); } }
private void cleanUp(File f) { if (!f.delete()) { showError("trouble deleting " + f.getName()); } else { // do something here? } }
// Raises the Save As dialog to have the user identify the location to save groups of things. public File determineSaveLocation(String dialogTitle, String defaultFolderName) { String defaultPath = this.getFileChooser().getCurrentDirectory().getPath(); if (!WWUtil.isEmpty(defaultPath)) defaultPath += File.separatorChar + defaultFolderName; File outFile; while (true) { this.getFileChooser().setDialogTitle(dialogTitle); this.getFileChooser().setSelectedFile(new File(defaultPath)); this.getFileChooser().setMultiSelectionEnabled(false); this.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int status = this.getFileChooser().showSaveDialog(this.getFrame()); if (status != JFileChooser.APPROVE_OPTION) return null; outFile = this.getFileChooser().getSelectedFile(); if (outFile == null) { this.showMessageDialog("No location selected", "No Selection", JOptionPane.ERROR_MESSAGE); continue; } break; } if (!outFile.exists()) //noinspection ResultOfMethodCallIgnored outFile.mkdir(); return outFile; }
private void onTransferFileClicked() { if (transferingFile) return; int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); showInfoMessage("Se selecciono el archivo " + file.getName()); try { lineCount = getFileLineCount(file); fileReader = new FileReader(file); linesTransfered = 0; headerSent = false; lineCountSent = false; transferingFile = true; transmitMessage("$save"); } catch (IOException e) { e.printStackTrace(); } } else { showInfoMessage("Se cancelo la transferencia de archivo"); } }
@Override public void actionPerformed(ActionEvent e) { if (td.getTabCount() > 0) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); int choose = f.showSaveDialog(getContentPane()); if (choose == JFileChooser.APPROVE_OPTION) { BufferedWriter brw = null; try { File file = f.getSelectedFile(); brw = new BufferedWriter(new FileWriter(file)); int i = td.getSelectedIndex(); TextDocument ta = (TextDocument) td.getComponentAt(i); ta.write(brw); ta.fileName = file.getName(); // 將檔案名稱更新為存檔的名稱 td.setTitleAt(td.getSelectedIndex(), ta.fileName); ta.file = file; ta.save = true; // 設定已儲存 System.out.println("Save as pass!"); td.setTitleAt(i, ta.fileName); // 更新標題名稱 } catch (Exception exc) { exc.printStackTrace(); } finally { try { brw.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } } else { JOptionPane.showMessageDialog(null, "沒有檔案可以儲存!"); } }
@Override public void actionPerformed(ActionEvent e) { JFileChooser f = new JFileChooser(); f.setFileFilter(new MyFileFilter()); // 設定檔案選擇器 int choose = f.showOpenDialog(getContentPane()); // 顯示檔案選取 if (choose == JFileChooser.OPEN_DIALOG) { // 有開啟檔案的話,開始讀檔 BufferedReader br = null; try { File file = f.getSelectedFile(); br = new BufferedReader(new FileReader(file)); TextDocument ta = new TextDocument(file.getName(), file); ta.addKeyListener(new SystemTrackSave()); ta.read(br, null); td.add(ta); td.setTitleAt(docCount++, file.getName()); } catch (Exception exc) { exc.printStackTrace(); } finally { try { br.close(); } catch (Exception ecx) { ecx.printStackTrace(); } } } }
/** * When the user has to specify file names, he can use wildcards (*, ?). This methods handles the * usage of these wildcards. * * @param path The path were to search * @param s Wilcards * @param sort Set to true will sort file names * @return An array of String which contains all files matching <code>s</code> in current * directory. */ public static String[] getWildCardMatches(String path, String s, boolean sort) { if (s == null) return null; String files[]; String filesThatMatch[]; String args = new String(s.trim()); ArrayList filesThatMatchVector = new ArrayList(); if (path == null) path = getUserDirectory(); files = (new File(path)).list(); if (files == null) return null; for (int i = 0; i < files.length; i++) { if (match(args, files[i])) { File temp = new File(getUserDirectory(), files[i]); filesThatMatchVector.add(new String(temp.getName())); } } Object[] o = filesThatMatchVector.toArray(); filesThatMatch = new String[o.length]; for (int i = 0; i < o.length; i++) filesThatMatch[i] = o[i].toString(); o = null; filesThatMatchVector = null; if (sort) Arrays.sort(filesThatMatch); return filesThatMatch; }
public void actionPerformed(ActionEvent e) { if (readOnly) { return; } JFileChooser fc = getFileChooser(); File currentDirectory = fc.getCurrentDirectory(); if (!currentDirectory.exists()) { JOptionPane.showMessageDialog( fc, newFolderParentDoesntExistText, newFolderParentDoesntExistTitleText, JOptionPane.WARNING_MESSAGE); return; } File newFolder; try { newFolder = fc.getFileSystemView().createNewFolder(currentDirectory); if (fc.isMultiSelectionEnabled()) { fc.setSelectedFiles(new File[] {newFolder}); } else { fc.setSelectedFile(newFolder); } } catch (IOException exc) { JOptionPane.showMessageDialog( fc, newFolderErrorText + newFolderErrorSeparator + exc, newFolderErrorText, JOptionPane.ERROR_MESSAGE); return; } fc.rescanCurrentDirectory(); }
private void saveBin() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(binFilter); fileChooser.setFileFilter(binFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == binFilter && !binFilter.accept(file)) { file = new File(file.getAbsolutePath() + binFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } FileOutputStream output = new FileOutputStream(file); for (char i : binary) { output.write(i & 0xff); output.write((i >> 8) & 0xff); } output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
private byte[] loadClassData(String className) throws IOException { Playground.println("Loading class " + className + ".class", warning); File f = new File(System.getProperty("user.dir") + "/" + className + ".class"); byte[] b = new byte[(int) f.length()]; new FileInputStream(f).read(b); return b; }
private void saveSrc() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(asmFilter); fileChooser.setFileFilter(asmFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == asmFilter && !asmFilter.accept(file)) { file = new File(file.getAbsolutePath() + asmFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } PrintStream output = new PrintStream(file); output.print(sourceTextarea.getText()); output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
public static int rollbackGUIConfigurationTransaction(String sConfigurationFileName) { String sConfigurationLockFile; File fFile; sConfigurationLockFile = new String(sConfigurationFileName + ".lck"); try { fFile = new File(URLDecoder.decode(sConfigurationLockFile, "UTF-8")); } catch (IOException e) { JOptionPane.showMessageDialog( null, "URLDecoder.decode failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE); return 1; } if (fFile.delete() == false) { JOptionPane.showMessageDialog( null, "fFile.delete on " + sConfigurationLockFile + " failed", "ConfigurationTransaction", JOptionPane.ERROR_MESSAGE); return 3; } return 0; }
/** * The ActionListener implementation * * @param event the event. */ public void actionPerformed(ActionEvent event) { String searchText = textField.getText().trim(); if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) { textPane.setText("Blank search text is not allowed for large IdTables."); } else { File outputFile = null; if (saveAs.isSelected()) { outputFile = chooser.getSelectedFile(); if (outputFile != null) { String name = outputFile.getName(); int k = name.lastIndexOf("."); if (k != -1) name = name.substring(0, k); name += ".txt"; File parent = outputFile.getAbsoluteFile().getParentFile(); outputFile = new File(parent, name); chooser.setSelectedFile(outputFile); } if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0); outputFile = chooser.getSelectedFile(); } textPane.setText(""); Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile); searcher.start(); } }
/** * Create/Replace a File * * @param Direct the Directory in which the File is made * @param Txt the Text to be written in the file */ public void createFile(String Direct, String Txt) { File f = new File(Direct + File_Name); if (f.isFile()) { // Check if this file already exists if (JOptionPane.showConfirmDialog( null, "This file already exists, do you wish to replace it?", "Replace", 0) != 0) { return; } // Delete file f.delete(); } try { // Replace/Create file f.createNewFile(); // If file preference set to "File with displayed text", write text to file if (Txt != null) { WriteFile(f, Txt); } Msgs.Type("File created", Display); } catch (Exception e) { Msgs.Type("Unable to create this file", Display); } }
protected void getImages() { File directory = new File(this.saveDirectory); // BufferedImage img = null; images = new ArrayList<String>(); if (directory.exists() && directory.isDirectory()) { // File[] files = directory.listFiles(); String[] files = directory.list(); for (int i = 0; i < files.length; i++) { // System.out.println(files[i]); // try { // if(files[i].getName().startsWith("cam")) if (files[i].startsWith("cam")) { // Windows spesific images.add(this.saveDirectory + "\\" + files[i]); /* img = ImageIO.read(files[i]); images.add(img);*/ } // } catch (IOException e) { // System.err.println("Failed on reading image. IOException."); // } } } System.out.println("Total image count = " + images.size()); gotImages = true; }
private void fixConfigSchema() { File configFile; File ctpDir = new File(directory, "CTP"); if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml"); else configFile = new File(directory, "config.xml"); if (configFile.exists()) { try { Document doc = getDocument(configFile); Element root = doc.getDocumentElement(); Element server = getFirstNamedChild(root, "Server"); moveAttributes(server, sslAttrs, "SSL"); moveAttributes(server, proxyAttrs, "ProxyServer"); moveAttributes(server, ldapAttrs, "LDAP"); if (programName.equals("ISN")) fixRSNAROOT(server); if (isMIRC(root)) fixFileServiceAnonymizerID(root); setFileText(configFile, toString(doc)); } catch (Exception ex) { cp.appendln(Color.red, "\nUnable to convert the config file schema."); cp.appendln(Color.black, ""); } } else { cp.appendln(Color.red, "\nUnable to find the config file to check the schema."); cp.appendln(Color.black, ""); } }
protected void setData(String strChecksum) { String strValue = (String) m_cmbPath.getSelectedItem(); if (strValue == null || strValue.equals("")) return; m_cmbChecksum.removeAllItems(); String strPath = strValue.substring(strValue.lastIndexOf("/") + 1); strPath = UtilB.unixPathToWindows(FileUtil.SYS_VNMR + "/p11/checksums/" + strPath); strPath = FileUtil.openPath(strPath); if (strPath != null) { File file = new File(strPath); String[] files = file.list(); int nSize = files.length; for (int i = 0; i < nSize; i++) { String strfile = files[i]; m_cmbChecksum.addItem(strfile); } int nIndex = strChecksum.lastIndexOf("/"); if (nIndex < 0) nIndex = strChecksum.lastIndexOf(File.separator); if (nIndex + 1 < strChecksum.length()) strChecksum = strChecksum.substring(nIndex + 1); m_cmbChecksum.setSelectedItem(strChecksum); } }
/** * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file. * * @param f The jar file to extract from. * @return a temporary file to which the plugin.xml file has been copied. */ public static File unpackPluginXML(File f) { InputStream in = null; OutputStream out = null; try { JarFile jar = new JarFile(f); ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE); if (entry == null) { return null; } File dest = File.createTempFile("jabref_plugin", ".xml"); dest.deleteOnExit(); in = new BufferedInputStream(jar.getInputStream(entry)); out = new BufferedOutputStream(new FileOutputStream(dest)); byte[] buffer = new byte[2048]; for (; ; ) { int nBytes = in.read(buffer); if (nBytes <= 0) break; out.write(buffer, 0, nBytes); } out.flush(); return dest; } catch (IOException ex) { ex.printStackTrace(); return null; } finally { try { if (out != null) out.close(); if (in != null) in.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
public void actionPerformed(ActionEvent e) { // Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); // Handle save button action. } else if (e.getSource() == saveButton) { int returnVal = fc.showSaveDialog(FileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); // This is where a real application would save the file. log.append("Saving: " + file.getName() + "." + newline); } else { log.append("Save command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); } }
public static boolean isInstallationHomeOrConfig( @NotNull final String installationHome, @NotNull final ConfigImportSettings settings) { if (new File(installationHome, OPTIONS_XML).exists()) return true; if (new File(installationHome, CONFIG_RELATED_PATH + OPTIONS_XML).exists()) return true; if (!new File(installationHome, BIN_FOLDER).exists()) { return false; } File libFolder = new File(installationHome, "lib"); boolean quickTest = false; String[] mainJarNames = settings.getMainJarNames(); for (String name : mainJarNames) { String mainJarName = StringUtil.toLowerCase(name) + ".jar"; //noinspection HardCodedStringLiteral if (new File(libFolder, mainJarName).exists()) { quickTest = true; break; } } if (!quickTest) return false; File[] files = getLaunchFilesCandidates(new File(installationHome), settings); for (File file : files) { if (file.exists()) return true; } return false; }
private static boolean validateOldConfigDir( @Nullable File installationHome, @Nullable File oldConfigDir, @NotNull ConfigImportSettings settings) { if (oldConfigDir == null) { if (installationHome != null) { JOptionPane.showMessageDialog( JOptionPane.getRootFrame(), ApplicationBundle.message( "error.invalid.installation.home", installationHome.getAbsolutePath(), settings.getProductName(ThreeState.YES))); } return false; } if (!oldConfigDir.exists()) { JOptionPane.showMessageDialog( JOptionPane.getRootFrame(), ApplicationBundle.message("error.no.settings.path", oldConfigDir.getAbsolutePath()), ApplicationBundle.message("title.settings.import.failed"), JOptionPane.WARNING_MESSAGE); return false; } return true; }
private void saveItem() { File f = new File("config.txt"); if (f.exists() && !f.isDirectory()) { try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("config.txt", true)))) { if (!searchName.getText().equals("") && !item.getText().equals("")) { out.println( searchName.getText() + "," + "http://www.reddit.com/r/hardwareswap/search?q=" + item.getText() + "&sort=new&restrict_sr=on"); addItem(); } else { results.setText("Please provide all info for Search Name and Item"); } } catch (IOException e1) { results.append("Error saving to file."); } } else { Main.checkFiles(); } }