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()); } }
@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(); } } } }
/** * public char[] jetPass(){ JPasswordField psf = new JPasswordField(); psf.grabFocus(); int opt = * JOptionPane.showConfirmDialog(frm, psf, "Password", JOptionPane.PLAIN_MESSAGE); if(opt == * JOptionPane.OK_OPTION) return psf.getPassword(); return null; } * * <p>public String jetString(String msg, String ttl){ return JOptionPane.showInputDialog(frm, * msg, ttl, JOptionPane.QUESTION_MESSAGE); }* */ public static String jobString(String job) { if (job.charAt(0) == IMPORT_FLAG) { String[] brk = job.split(",", 4); // 4 parts to an import string File inf = new File(brk[1]); return "import " + inf.getName(); } else { String[] brk = job.split(",", 3); // 3 parts to export string File plf = new File(brk[2]); return "export " + plf.getName(); } }
public boolean edtImport(File fi, String date, String tags) { if (!fi.exists()) { System.err.println("import: file " + fi.getAbsolutePath() + " doesnt exist"); return false; } String pname = fi.getName(); if (store.containsEntry(pname)) { System.err.println("import: already have a file named " + pname); return false; } long size = fi.length() / KILOBYTE; File save = sec.encryptMainFile(fi, storeLocs.get(0), true); if (save == null) { System.err.println("import: Encryption failure"); return false; } if (checkImports) { boolean success = true; File checkfi = new File(idx + ".check"); File checkOut = sec.encryptSpecialFile(save, checkfi, false); if (checkOut == null) success = false; else { String fiHash = sec.digest(fi); String outHash = sec.digest(checkOut); if (fiHash == null || outHash == null || fiHash.length() < 1 || !fiHash.equals(outHash)) success = false; } checkfi.delete(); if (!success) { save.delete(); if (JOptionPane.showConfirmDialog( frm, "Confirming " + fi.getName() + "failed\n\n - Would you like to re-import the file?", "Import failed", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { String j = impJob(fi, date, tags); synchronized (jobs) { if (priorityExport) jobs.addLast(j); else jobs.addFirst(j); } } return false; } } if (!fi.delete()) { System.err.println("import: Couldnt delete old file - continuing"); } store.add(save.getName(), pname, date, size, tags, 0); needsSave = true; return true; }
public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("clear")) { scriptArea.setText(""); } else if (ae.getActionCommand().equals("save")) { // fc.setCurrentDirectory(new File("/Users/jc/Documents/LOGO")); int bandera = fileChooser.showSaveDialog(myWindow); if (bandera == JFileChooser.APPROVE_OPTION) { String cadena1 = scriptArea.getText(); String cadena2 = cadena1.replace("\r", "\n"); System.out.println(cadena1); try { BufferedWriter script = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile() + ".txt")); script.write(cadena2); script.close(); } catch (Exception ex) { ex.printStackTrace(); } File file = fileChooser.getSelectedFile(); JOptionPane.showMessageDialog(myWindow, "File: " + file.getName() + " Saved.\n"); } scriptArea.setCaretPosition(scriptArea.getDocument().getLength()); } else if (ae.getActionCommand().equals("quit")) { myWindow.setVisible(false); } else if (ae.getActionCommand().equals("load")) { // String arreglo[] = new String[100]; // int i = 0; // fc.setCurrentDirectory(new File("/Users/jc/Documents/LOGO")); int bandera = fileChooser.showOpenDialog(myWindow); if (bandera == JFileChooser.APPROVE_OPTION) { try { BufferedReader script = new BufferedReader(new FileReader(fileChooser.getSelectedFile())); scriptArea.read(script, null); script.close(); scriptArea.requestFocus(); } catch (Exception ex) { ex.printStackTrace(); } File file = fileChooser.getSelectedFile(); myWindow.setTitle(file.getName()); JOptionPane.showMessageDialog(myWindow, file.getName() + ": File loaded.\n"); scriptArea.setCaretPosition(scriptArea.getDocument().getLength()); } } else if (ae.getActionCommand().equals("run")) { System.out.println("LEL"); } }
private void cleanUp(File f) { if (!f.delete()) { showError("trouble deleting " + f.getName()); } else { // do something here? } }
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, "沒有檔案可以儲存!"); } }
public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); if (JOkCancelPanel.OK.equals(cmd)) { // update evaluator evaluator.name = tfName.getText(); evaluator.type = (byte) cbType.getSelectedIndex(); evaluator.ignoreDiagonals = cbDiagonals.isSelected(); evaluator.investments = (byte) cbInvestment.getSelectedIndex(); evaluator.orgFile = orgFile; setVisible(false); } else if (JOkCancelPanel.CANCEL.equals(cmd)) { // don't update evaluator setVisible(false); } else if (CMD_CHOOSE_FILE.equals(cmd)) { // get a file dialog JFrame f = new JFrame(); JFileChooser jfc = Application.getFileChooser(); int res = jfc.showOpenDialog(f); Application.setWorkingDirectory(jfc.getCurrentDirectory()); if (res == JFileChooser.CANCEL_OPTION) { return; } orgFile = jfc.getSelectedFile(); lOrgFileName.setText("File: " + orgFile.getName()); } }
protected void _showDialog_() { String strMethod = "_showDialog_()"; String[] strsTypeFileShkCur = _getTypeFileShkCur(); if (strsTypeFileShkCur == null) MySystem.s_printOutExit(this, strMethod, "nil strsTypeFileShkCur"); String strFileDesc = _getDescFileShkCur(); if (strFileDesc == null) MySystem.s_printOutExit(this, strMethod, "nil strFileDesc"); // ---- File fle = null; String strButtonTextOk = "Save file"; fle = S_FileChooserUI.s_getSaveFile( super._frmParent_, strButtonTextOk, strsTypeFileShkCur, strFileDesc, com.google.code.p.keytooliui.ktl.io.S_FileExtensionUI.f_s_strDirNameDefaultShk); if (fle == null) { // cancelled return; } if (!_assignValues(fle)) MySystem.s_printOutExit(this, strMethod, "failed, fle.getName()=" + fle.getName()); }
/** * Load a file of a particular type. It's a pretty standard helper function, which uses DarwinCSV * and setCurrentCSV(...) to make file loading happen with messaging and whatnot. We can also * reset the display: just call loadFile(null). * * @param file The file to load. * @param type The type of file (see DarwinCSV's constants). */ private void loadFile(File file, short type) { // If the file was reset, reset the display and keep going. if (file == null) { mainFrame.setTitle(basicTitle); setCurrentCSV(null); return; } // Load up a new DarwinCSV and set current CSV. try { setCurrentCSV(new DarwinCSV(file, type)); } catch (IOException ex) { MessageBox.messageBox( mainFrame, "Could not read file '" + file + "'", "Unable to read file '" + file + "': " + ex); } // Set the main frame title, based on the filename and the index. mainFrame.setTitle( basicTitle + ": " + file.getName() + " (" + String.format("%,d", currentCSV.getRowIndex().getRowCount()) + " rows)"); }
private String getCurrentShortFilename() { if (_srcBundlePath != null) { File f = new File(_srcBundlePath); return f.getName(); } return "Untitled"; }
/** * 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(); } }
public void totalExport() { File expf = new File("export"); if (expf.exists()) rmrf(expf); expf.mkdirs(); for (int sto = 0; sto < storeLocs.size(); sto++) { try { String sl = storeLocs.get(sto).getAbsolutePath().replaceAll("/", "-").replaceAll("\\\\", "-"); File estore = new File(expf, sl); estore.mkdir(); File log = new File(estore, LIBRARY_NAME); PrintWriter pw = new PrintWriter(log); for (int i = 0; i < store.getRowCount(); i++) if (store.curStore(i) == sto) { File enc = store.locate(i); File dec = sec.prepareMainFile(enc, estore, false); pw.println(dec.getName()); pw.println(store.getValueAt(i, Storage.COL_DATE)); pw.println(store.getValueAt(i, Storage.COL_TAGS)); synchronized (jobs) { jobs.addLast(expJob(enc, dec)); } } pw.close(); } catch (IOException exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frm, "Exporting Failed"); return; } } JOptionPane.showMessageDialog(frm, "Exporting to:\n " + expf.getAbsolutePath()); }
@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; }
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); }
@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 boolean accept(File pathname) { if (pathname.isDirectory()) return true; else { if (pathname.getName().indexOf(".scl") != -1) return true; else return false; } }
private boolean checkForSave() { // build warning message String message; if (file == null) { message = "File has been modified. Save changes?"; } else { message = "File \"" + file.getName() + "\" has been modified. Save changes?"; } // show confirm dialog int r = JOptionPane.showConfirmDialog( this, new JLabel(message), "Warning!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (r == JOptionPane.YES_OPTION) { // Save File if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { // write the file physWriteTextFile(fileChooser.getSelectedFile(), textView.getText()); } else { // user cancelled save after all return false; } } return r != JOptionPane.CANCEL_OPTION; }
public Boolean isHidden(File f) { String name = f.getName(); if (name != null && name.charAt(0) == '.') { return Boolean.TRUE; } else { return Boolean.FALSE; } }
private String getFileExt(File f) { String name = f.getName(); int pos = name.lastIndexOf('.'); if (pos > 0) { return name.substring(pos); } return ""; }
public boolean accept(File f) { if (f == null) { return false; } if (f.isDirectory()) { return true; } return pattern.matcher(f.getName()).matches(); }
/** * Returns the string, showing information for the given file. * * @param file the file * @return the name of the given file */ protected String getFileLabel(File file) { String fileName = file.getName(); long fileSize = file.length(); ByteFormat format = new ByteFormat(); String text = format.format(fileSize); return fileName + " (" + text + ")"; }
public boolean accept(File f) { if (f.isDirectory()) { return true; } String fn = f.getName(); if (fn.toLowerCase().endsWith(".java") || fn.toLowerCase().endsWith(".txt")) { return true; } return false; }
private String physReadTextFile(File file) { // physically read text file try { BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuffer tmp = new StringBuffer(); while (input.ready()) { tmp.append(input.readLine()); tmp.append("\n"); } return tmp.toString(); } catch (FileNotFoundException e) { // not sure how this can happen showErrorDialog("Unable to load \"" + file.getName() + "\" (file not found)"); } catch (IOException e) { // This happens if e.g. file already exists and // we do not have write permissions showErrorDialog("Unable to load \"" + file.getName() + "\" (I/O error)"); } return new String(""); }
void refresh() { if (currentFile != null) { String fileName = currentFile.getName(); if (fileName.endsWith("." + EXTENSION)) { fileName = fileName.substring(0, fileName.length() - 1 - EXTENSION.length()); } setTitle(MessageFormat.format(strings.getString("main.caption_named_file"), fileName)); } else { setTitle(strings.getString("main.caption_unnamed_file")); } }
@Override public void approveSelection() { File file = getSelectedFile(); if (file != null) { FileFilter filter = getFileFilter(); if (filter != null && filter instanceof FileNameExtensionFilter) { String[] extensions = ((FileNameExtensionFilter) filter).getExtensions(); boolean goodExt = false; for (String ext : extensions) { if (file.getName().toLowerCase().endsWith("." + ext.toLowerCase())) { goodExt = true; break; } } if (!goodExt) { file = new File(file.getParent(), file.getName() + "." + extensions[0]); } } if (file.exists()) { String okStr = Messages.FILE_CHOOSER_FILE_EXISTS_OK_OPTION; String cancelStr = Messages.FILE_CHOOSER_FILE_EXISTS_CANCEL_OPTION; int ret = JOptionPane.showOptionDialog( this, Resources.format(Messages.FILE_CHOOSER_FILE_EXISTS_MESSAGE, file.getName()), Messages.FILE_CHOOSER_FILE_EXISTS_TITLE, JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new Object[] {okStr, cancelStr}, okStr); if (ret != JOptionPane.OK_OPTION) { return; } } setSelectedFile(file); } super.approveSelection(); }
/** Set the template file path. */ private boolean setTemplateFile(String pathStr) { File templateFile = new File(templateCh.getSelectedPath(pathStr)); if (!templateFile.getName().toLowerCase().endsWith(".tpl")) { final String templateCaption = ResourceHandler.getMessage("nottemplatefile_dialog.caption"); MessageFormat formatter = new MessageFormat(ResourceHandler.getMessage("nottemplatefile_dialog.info0")); final String errorMessage = formatter.format(new Object[] {templateFile.getName()}); String defaultTemplateName = PluginConverter.getDefaultTemplateFileName(); JOptionPane.showMessageDialog(this, errorMessage, templateCaption, JOptionPane.ERROR_MESSAGE); templateCh.select(templateCh.getPreviousSelection()); return false; } try { converter.setTemplateFilePath(templateCh.getSelectedPath(pathStr)); } catch (FileNotFoundException e) { // TO-DO: found it, but it's not a file. // TO-DO: Throw up a Dialog -- "Not a valid file, resetting to default file" final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0"); MessageFormat formatter; String info_msg; if (pathStr.equals("")) { info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5"); } else { formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1")); info_msg = formatter.format(new Object[] {pathStr}); } final String info = info_msg; JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } return true; }
public void saveFile() { if (file == null) { // first save file, so prompt for name. saveFileAs(); } else { // file already named so just write it. physWriteTextFile(file, textView.getText()); // update status statusView.setText(" Saved file \"" + file.getName() + "\"."); // reset dirty bit dirty = false; } }
private void openFile() { JFileChooser chooser = new JFileChooser("c:\\Javafiles"); int result = chooser.showOpenDialog(this); if (result == JFileChooser.CANCEL_OPTION) JOptionPane.showMessageDialog(this, "The dialog was cancelled."); else try { File file = chooser.getSelectedFile(); JOptionPane.showMessageDialog(this, "File name: " + file.getName()); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Error opening input file " + e.toString()); } }