public void valueChanged(ListSelectionEvent evt) { if (!evt.getValueIsAdjusting()) { JFileChooser chooser = getFileChooser(); FileSystemView fsv = chooser.getFileSystemView(); JList list = (JList) evt.getSource(); int fsm = chooser.getFileSelectionMode(); boolean useSetDirectory = usesSingleFilePane && (fsm == JFileChooser.FILES_ONLY); if (chooser.isMultiSelectionEnabled()) { File[] files = null; Object[] objects = list.getSelectedValues(); if (objects != null) { if (objects.length == 1 && ((File) objects[0]).isDirectory() && chooser.isTraversable(((File) objects[0])) && (useSetDirectory || !fsv.isFileSystem(((File) objects[0])))) { setDirectorySelected(true); setDirectory(((File) objects[0])); } else { ArrayList<File> fList = new ArrayList<File>(objects.length); for (Object object : objects) { File f = (File) object; boolean isDir = f.isDirectory(); if ((chooser.isFileSelectionEnabled() && !isDir) || (chooser.isDirectorySelectionEnabled() && fsv.isFileSystem(f) && isDir)) { fList.add(f); } } if (fList.size() > 0) { files = fList.toArray(new File[fList.size()]); } setDirectorySelected(false); } } chooser.setSelectedFiles(files); } else { File file = (File) list.getSelectedValue(); if (file != null && file.isDirectory() && chooser.isTraversable(file) && (useSetDirectory || !fsv.isFileSystem(file))) { setDirectorySelected(true); setDirectory(file); if (usesSingleFilePane) { chooser.setSelectedFile(null); } } else { setDirectorySelected(false); if (file != null) { chooser.setSelectedFile(file); } } } } }
/** Initialize the panel UI component values from the current site profile settings. */ public void updatePanel() { { File dir = pApp.getHomeDirectory(); if (dir == null) { String home = System.getProperty("user.home"); if (home != null) { File hdir = new File(home); if ((hdir != null) && hdir.isDirectory()) dir = hdir.getParentFile(); } } if (dir == null) dir = new File("/home"); pHomeDirComp.setDir(dir); } { File dir = pApp.getTemporaryDirectory(); if (dir == null) dir = new File("/var/tmp"); pTempDirComp.setDir(dir); } { File dir = pApp.getUnixJavaHome(); if (dir == null) dir = new File(pApp.getJavaHome()); pJavaHomeDirComp.setDir(dir); } pJavadocDirComp.setDir(pApp.getUnixLocalJavadocDirectory()); pExtraJavaLibsComp.setJars(pApp.getUnixLocalJavaLibraries()); }
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; }
public boolean accept(File pathname) { if (pathname.isDirectory()) return true; else { if (pathname.getName().indexOf(".scl") != -1) return true; else return false; } }
public boolean accept(File f) { if (f == null) { return false; } if (f.isDirectory()) { return true; } return pattern.matcher(f.getName()).matches(); }
/** * The FileEvent listener. * * @param event the event. */ public void fileEventOccurred(FileEvent event) { File file = event.getFile(); if (file != null) { String dirPath; if (file.isDirectory()) dirPath = file.getAbsolutePath(); else dirPath = file.getParentFile().getAbsolutePath(); properties.setProperty("directory", dirPath); } else properties.remove("directory"); }
protected void fileNew() { if (currentFile != null) { if (!currentFile.isDirectory()) { currentFile = currentFile.getParentFile(); } } graph.clear(); gp.update(gp.getGraphics()); }
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; }
public String getTypeDescription(File f) { String type = getFileChooser().getFileSystemView().getSystemTypeDescription(f); if (type == null) { if (f.isDirectory()) { type = directoryDescriptionText; } else { type = fileDescriptionText; } } return type; }
protected void fileSave() { if (currentFile == null) { fileSaveAs(); } else { if (currentFile.isDirectory()) { fileSaveAs(); } else { graph.saveAll(currentFile); gp.update(gp.getGraphics()); } } }
/** Returns false if Exception is thrown. */ private boolean setDirectory() { String pathStr = dirTF.getText().trim(); if (pathStr.equals("")) pathStr = System.getProperty("user.dir"); try { File dirPath = new File(pathStr); if (!dirPath.isDirectory()) { if (!dirPath.exists()) { if (recursiveCheckBox.isSelected()) throw new NotDirectoryException(dirPath.getAbsolutePath()); else throw new NotFileException(dirPath.getAbsolutePath()); } else { convertSet.setFile(dirPath); convertSet.setDestinationPath(dirPath.getParentFile()); } } else { // Set the descriptors setMatchingFileNames(); FlexFilter flexFilter = new FlexFilter(); flexFilter.addDescriptors(descriptors); flexFilter.setFilesOnly(!recursiveCheckBox.isSelected()); convertSet.setSourcePath(dirPath, flexFilter); convertSet.setDestinationPath(dirPath); } } catch (NotDirectoryException e1) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption1"); MessageFormat formatter; String info_msg; if (pathStr.equals("")) { info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5"); } else { formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info0")); info_msg = formatter.format(new Object[] {pathStr}); } final String info = info_msg; JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } catch (NotFileException e2) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0"); MessageFormat formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1")); final String info = formatter.format(new Object[] {pathStr}); JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } return true; // no exception thrown }
private boolean _assignValues(File fle) { String strMethod = "_assignValues(fle)"; if (fle == null) { MySystem.s_printOutError(this, strMethod, "nil fle"); return false; } if (!fle.exists()) { MySystem.s_printOutWarning( this, strMethod, "! fle.exists(), fle.getAbsolutePath()=" + fle.getAbsolutePath()); String strBody = fle.getAbsolutePath(); strBody += ":\nDirectory not found."; OPAbstract.s_showDialogWarning(super._frmParent_, strBody); return true; } if (!fle.isDirectory()) // statement should never be reached!!! { MySystem.s_printOutWarning( this, strMethod, "! fle.isDirectory(), fle.getAbsolutePath()=" + fle.getAbsolutePath()); String strBody = fle.getAbsolutePath(); strBody += ":\n not a directory."; OPAbstract.s_showDialogWarning(super._frmParent_, strBody); return true; } if (super._tfdCurSelection_ == null) { MySystem.s_printOutError(this, strMethod, "nil super._tfdCurSelection_"); return false; } super._tfdCurSelection_.setText(fle.getAbsolutePath()); super._setSelectedValue_(true); if (!_enableButtonsSelectionDone_()) { MySystem.s_printOutError(this, strMethod, "failed"); return false; } // -- // ending return true; }
@Override public boolean accept(File file) { if (file.isDirectory()) { return true; } String name = file.getName().toLowerCase(); for (int i = 0; i < extensions.length; ++i) { if (name.endsWith(extensions[i])) { return true; } } return false; }
public static boolean deleteAll(File file) { boolean b = true; if ((file != null) && file.exists()) { if (file.isDirectory()) { try { File[] files = file.listFiles(); for (File f : files) b &= deleteAll(f); } catch (Exception e) { return false; } } b &= file.delete(); } return b; }
public static void main(String[] args) { // read arguments and respond correctly File in; File out; String tileDirectory; if (args.length == 0 || args.length > 2) { in = null; out = null; tileDirectory = ""; System.err.println("Incorrect number of arguments. Required: Filename (tileset path)"); System.exit(0); } else if (args.length == 1) { // load old file in = new File(args[0]); out = in; Scanner s = null; try { s = new Scanner(in); } catch (FileNotFoundException e) { System.out.println("Could not find input file."); System.exit(0); } tileDirectory = s.nextLine(); } else { in = null; out = new File(args[0]); tileDirectory = args[1]; try { File f = new File(tileDirectory); if (!f.isDirectory()) { throw new IOException("Tileset does not exist"); } } catch (IOException e) { System.err.println(e); System.out.println("This error is likely thanks to an invalid tileset path"); System.exit(0); } } MapBuilder test = new MapBuilder("Map Editor", in, out, tileDirectory); // Build GUI SwingUtilities.invokeLater( new Runnable() { public void run() { test.CreateAndDisplayGUI(); } }); }
protected void fileSaveSimple() { JFileChooser chooser = null; if (currentFile == null) { chooser = new JFileChooser(startDirectory); } else { chooser = new JFileChooser(currentFile); if (!currentFile.isDirectory()) { chooser.setSelectedFile(currentFile); } } int returnVal = chooser.showSaveDialog(gw); if (returnVal == JFileChooser.APPROVE_OPTION) { currentFile = chooser.getSelectedFile(); graph.saveSimple(currentFile); } }
private void browseAction() { if (selectedPath == null) { selectedPath = System.getenv("ROPE_SOURCES_DIR"); if (selectedPath != null) { File dir = new File(selectedPath); if (!dir.exists() || !dir.isDirectory()) { String message = String.format( "The sources path set in environment variable ROPE_SOURCES_DIR is not avaliable.\n%s", selectedPath); JOptionPane.showMessageDialog(null, message, "ROPE", JOptionPane.WARNING_MESSAGE); selectedPath = null; } else { System.out.println("Source folder path set from ROPE_SOURCES_DIR: " + selectedPath); } } if (selectedPath == null) { selectedPath = System.getProperty("user.dir"); System.out.println("Source folder path set to current directory: " + selectedPath); } } Vector<RopeFileFilter> filters = new Vector<RopeFileFilter>(); filters.add( new RopeFileFilter( new String[] {".a", ".asm", ".aut", ".s"}, "Assembly files (*.a *.asm *.aut *.s)")); filters.add(new RopeFileFilter(new String[] {".m", ".mac"}, "Macro files (*.m *.mac)")); filters.add(new RopeFileFilter(new String[] {".lst"}, "List files (*.lst)")); filters.add(new RopeFileFilter(new String[] {".txt"}, "Text files (*.txt)")); RopeFileChooser chooser = new RopeFileChooser(selectedPath, null, filters); chooser.setDialogTitle("Source document selection"); chooser.setFileFilter(filters.firstElement()); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); File file = chooser.open(this, fileText); if (file != null) { if (loadSourceFile(file)) { mainFrame.showExecWindow(baseName); } } }
private void listFiles(String basePath, String path, String extension, Vector<String> vector) { File folder = new File(path); String[] list = folder.list(); if (list != null) { for (String item : list) { if (item.charAt(0) == '.') continue; File file = new File(path, item); String newPath = file.getAbsolutePath(); if (newPath.startsWith(basePath)) { newPath = newPath.substring(basePath.length()); } if (extension == null || item.toLowerCase().endsWith(extension)) { vector.add(newPath); } if (file.isDirectory()) { listFiles(basePath, file.getAbsolutePath(), extension, vector); } } } }
/** * Load the file names of all files in the given directory. * * @param dirName Directory (folder) name. * @param suffix File suffix of interest. * @return The names of files found. */ private String[] findFiles(String dirName, String suffix) { File dir = new File(dirName); if (dir.isDirectory()) { String[] allFiles = dir.list(); if (suffix == null) { return allFiles; } else { List<String> selected = new ArrayList<String>(); for (String filename : allFiles) { if (filename.endsWith(suffix)) { selected.add(filename); } } return selected.toArray(new String[selected.size()]); } } else { System.out.println("Error: " + dirName + " must be a directory"); return null; } }
public Icon getIcon(File f) { Icon icon = getCachedIcon(f); if (icon != null) { return icon; } icon = fileIcon; if (f != null) { FileSystemView fsv = getFileChooser().getFileSystemView(); if (fsv.isFloppyDrive(f)) { icon = floppyDriveIcon; } else if (fsv.isDrive(f)) { icon = hardDriveIcon; } else if (fsv.isComputerNode(f)) { icon = computerIcon; } else if (f.isDirectory()) { icon = directoryIcon; } } cacheIcon(f, icon); return icon; }
boolean tryDir(String d) { ClassLoader L = getClass().getClassLoader(); File p = new File(d, PACKAGE); System.out.println("Try " + p); if (!p.exists() || !p.isDirectory()) return false; for (File f : p.listFiles()) { String s = f.getName(); if (!s.endsWith(".class")) continue; String name = s.substring(0, s.length() - 6); try { Class<?> c = L.loadClass(PACKAGE + "." + name); if (!Animator.class.isAssignableFrom(c)) continue; Animator a = (Animator) c.newInstance(); a.container().setPreferredSize(DIM); map.put(name, a); System.out.println(" " + name); // ClassNotFoundException InstantiationException IllegalAccessException } catch (Exception e) { continue; } } return map.size() > 0; }
public static boolean rmrf(File fi) { if (fi.isDirectory()) { boolean done = true; for (File subfi : fi.listFiles()) { if (!rmrf(subfi)) { done = false; } } if (!done) return false; return fi.delete(); } else { boolean done = true; for (int i = 0; i < 10; i++) { done = fi.delete(); if (done) break; try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } } return done; } }
public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == binfo) { JOptionPane.showMessageDialog( frame, "Programme crée par Sarathai\n" + "Licence creative commons\n" + "\n" + "Pour envoyer des fichiers sur le serveur, cliquer d'abord sur le bouton ajouter,\n" + "puis sélectionnez le dossier ou fichier à ajouter. Répétez cette opération autant de foi que nécessaire.\n" + "Puis cliquez sur le bouton envoyer en ayant d'abord rempli les champs de l'adresse ip et du port.\n" + "\n" + "Pour recevoir des fichiers sauvegardés sur le serveur, cliquez sur le bouton recevoir,\n" + "puis sélectionnez le ou les fichier(s) voulu(s) dans la liste de gauche, et enfin recliquez\n" + "sur le bouton recevoir pour importer les fichiers.\n" + "\n" + "Pour toutes les infos, bien lire le texte qui s'affiche dans le champ de texte en bas.", "Informations", JOptionPane.INFORMATION_MESSAGE); } else if (src == ajouter) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(chooser.getAcceptAllFileFilter()); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); int i = chooser.showOpenDialog(Fenetre.frame); if (i == JFileChooser.APPROVE_OPTION) { frame.setCursor(waitCursor); File file = chooser.getSelectedFile(); if (file.isDirectory()) { name = file.getAbsolutePath().toString() + sep; selection.addElement(name); new WhatIDo("Ajouté à la séléction", name); } else { name = file.getAbsolutePath().toString(); selection.addElement(name); new WhatIDo("Ajouté à la séléction", name); } liste.updateUI(); enlever.setEnabled(true); frame.setCursor(Cursor.getDefaultCursor()); } } else if (src == enlever) { try { int j = liste.getSelectedIndex(); new WhatIDo("Supprimé de la séléction", selection.elementAt(j).toString()); selection.removeElementAt(j); } catch (ArrayIndexOutOfBoundsException e1) { new WhatIDo("Supprimé de la séléction", selection.elementAt(0).toString()); selection.removeElementAt(0); } if (selection.size() == 0) { selection.clear(); liste.clearSelection(); enlever.setEnabled(false); } liste.updateUI(); } else if (src == bquitter) { System.exit(0); } else if (src == bnouveau) { selection.clear(); liste.clearSelection(); liste.updateUI(); new WhatIDo("Nouvelle sauvegarde"); } else if (src == benvoyer) { if (!selection.isEmpty()) { new Envoyer(selection); } else { new WhatIDo("Veuillez ajouter des fichiers ou dossiers"); } } else if (src == brecevoir) { if (!liste.isSelectionEmpty()) { Vector<String> vec = new Vector<String>(); for (int i : liste.getSelectedIndices()) { vec.addElement(selection.elementAt(i)); } new Recevoir(vec); } else { new Recevoir(); } } }
protected void filePNG() { JFileChooser chooser = null; File pngFile = null; if (currentFile == null) { chooser = new JFileChooser(startDirectory); } else { pngFile = new File(currentFile.getName() + ".png"); chooser = new JFileChooser(pngFile); if (!currentFile.isDirectory()) { chooser.setSelectedFile(currentFile); } } if (pngFile == null) return; try { BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); paint(image.getGraphics()); ImageIO.write(image, "png", pngFile); } catch (Exception e) { } return; /* JFileChooser chooser = null; File pngFile = null; if (currentFile == null) { chooser = new JFileChooser(startDirectory); } else { pngFile = new File(currentFile.getName()+".png"); chooser = new JFileChooser(pngFile); if (!currentFile.isDirectory()) { chooser.setSelectedFile(currentFile); } } int returnVal = chooser.showSaveDialog(gw); if (returnVal == JFileChooser.APPROVE_OPTION) { File pngFile = chooser.getSelectedFile(); int maxX = Integer.MIN_VALUE; int minX = Integer.MAX_VALUE; int maxY = Integer.MIN_VALUE; int minY = Integer.MAX_VALUE; while(Node node : getNodes()) { if(node.getX() > maxX) { maxX = node.getX(); } if(node.getX() < minX) { minX = node.getX(); } if(node.getY() > maxY) { maxY = node.getY(); } if(node.getY() < minY) { minY = node.getY(); } } BufferedImage image = new BufferedImage(maxX-minX+50,maxY-minY+50,BufferedImage.TYPE_INT_RGB); ImageIO.write(image,"png",pngFile); } */ }
public Ssys3() { store = new Storage(); tableSorter = new TableRowSorter<Storage>(store); jobs = new LinkedList<String>(); makeGUI(); frm.setSize(800, 600); frm.addWindowListener( new WindowListener() { public void windowActivated(WindowEvent evt) {} public void windowClosed(WindowEvent evt) { try { System.out.println("joining EDT's"); for (EDT edt : encryptDecryptThreads) { edt.weakStop(); try { edt.join(); System.out.println(" - joined"); } catch (InterruptedException e) { System.out.println(" - Not joined"); } } System.out.println("saving storage"); store.saveAll(tempLoc); } catch (IOException e) { e.printStackTrace(); System.err.println( "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nFailed to save properly\n\n!!!!!!!!!!!!!!!!!!!!!!!!!"); System.exit(1); } clean(); System.exit(0); } public void windowClosing(WindowEvent evt) { windowClosed(evt); } public void windowDeactivated(WindowEvent evt) {} public void windowDeiconified(WindowEvent evt) {} public void windowIconified(WindowEvent evt) {} public void windowOpened(WindowEvent evt) {} }); ImageIcon ico = new ImageIcon(ICON_NAME); frm.setIconImage(ico.getImage()); frm.setLocationRelativeTo(null); frm.setVisible(true); // load config storeLocs = new ArrayList<File>(); String ossl = "openssl"; int numThreadTemp = 2; boolean priorityDecryptTemp = true; boolean allowExportTemp = false; boolean checkImportTemp = true; try { Scanner sca = new Scanner(CONF_FILE); while (sca.hasNextLine()) { String ln = sca.nextLine(); if (ln.startsWith(CONF_SSL)) { ossl = ln.substring(CONF_SSL.length()); } else if (ln.startsWith(CONF_THREAD)) { try { numThreadTemp = Integer.parseInt(ln.substring(CONF_THREAD.length())); } catch (Exception exc) { // do Nothing } } else if (ln.equals(CONF_STORE)) { while (sca.hasNextLine()) storeLocs.add(new File(sca.nextLine())); } else if (ln.startsWith(CONF_PRIORITY)) { try { priorityDecryptTemp = Boolean.parseBoolean(ln.substring(CONF_PRIORITY.length())); } catch (Exception exc) { // do Nothing } } else if (ln.startsWith(CONF_EXPORT)) { try { allowExportTemp = Boolean.parseBoolean(ln.substring(CONF_EXPORT.length())); } catch (Exception exc) { // do Nothing } } else if (ln.startsWith(CONF_CONFIRM)) { try { checkImportTemp = Boolean.parseBoolean(ln.substring(CONF_CONFIRM.length())); } catch (Exception exc) { // do Nothing } } } sca.close(); } catch (IOException e) { } String osslWorks = OpenSSLCommander.test(ossl); while (osslWorks == null) { ossl = JOptionPane.showInputDialog( frm, "Please input the command used to run open ssl\n We will run \"<command> version\" to confirm\n Previous command: " + ossl, "Find open ssl", JOptionPane.OK_CANCEL_OPTION); if (ossl == null) { System.err.println("Refused to provide openssl executable location"); System.exit(1); } osslWorks = OpenSSLCommander.test(ossl); if (osslWorks == null) JOptionPane.showMessageDialog( frm, "Command " + ossl + " unsuccessful", "Unsuccessful", JOptionPane.ERROR_MESSAGE); } if (storeLocs.size() < 1) JOptionPane.showMessageDialog( frm, "Please select an initial sotrage location\nIf one already exists, or there are more than one, please select it"); while (storeLocs.size() < 1) { JFileChooser jfc = new JFileChooser(); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (jfc.showOpenDialog(frm) != JFileChooser.APPROVE_OPTION) { System.err.println("Refused to provide an initial store folder"); System.exit(1); } File sel = jfc.getSelectedFile(); if (sel.isDirectory()) storeLocs.add(sel); } numThreads = numThreadTemp; priorityExport = priorityDecryptTemp; allowExport = allowExportTemp; checkImports = checkImportTemp; try { PrintWriter pw = new PrintWriter(CONF_FILE); pw.println(CONF_SSL + ossl); pw.println(CONF_THREAD + numThreads); pw.println(CONF_PRIORITY + priorityExport); pw.println(CONF_EXPORT + allowExport); pw.println(CONF_CONFIRM + checkImports); pw.println(CONF_STORE); for (File fi : storeLocs) { pw.println(fi.getAbsolutePath()); } pw.close(); } catch (IOException e) { System.err.println("Failed to save config"); } File chk = null; for (File fi : storeLocs) { File lib = new File(fi, LIBRARY_NAME); if (lib.exists()) { chk = lib; // break; } } char[] pass = null; if (chk == null) { JOptionPane.showMessageDialog( frm, "First time run\n Create your password", "Create Password", JOptionPane.INFORMATION_MESSAGE); char[] p1 = askPassword(); char[] p2 = askPassword(); boolean same = p1.length == p2.length; for (int i = 0; i < Math.min(p1.length, p2.length); i++) { if (p1[i] != p2[i]) same = false; } if (same) { JOptionPane.showMessageDialog( frm, "Password created", "Create Password", JOptionPane.INFORMATION_MESSAGE); pass = p1; } else { JOptionPane.showMessageDialog( frm, "Passwords dont match", "Create Password", JOptionPane.ERROR_MESSAGE); System.exit(1); } } else { pass = askPassword(); } sec = OpenSSLCommander.getCommander(chk, pass, ossl); if (sec == null) { System.err.println("Wrong Password"); System.exit(1); } store.useSecurity(sec); store.useStorage(storeLocs); tempLoc = new File("temp"); if (!tempLoc.exists()) tempLoc.mkdirs(); // load stores try { store.loadAll(tempLoc); store.fireTableDataChanged(); } catch (IOException e) { System.err.println("Storage loading failure"); System.exit(1); } needsSave = false; encryptDecryptThreads = new EDT[numThreads]; for (int i = 0; i < encryptDecryptThreads.length; i++) { encryptDecryptThreads[i] = new EDT(i); encryptDecryptThreads[i].start(); } updateStatus(); txaSearch.grabFocus(); }
public void secureImport() { JFileChooser imp = new JFileChooser(); imp.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); imp.setMultiSelectionEnabled(true); int ret = imp.showOpenDialog(frm); if (ret != JFileChooser.APPROVE_OPTION) { return; } File[] fis = imp.getSelectedFiles(); ArrayList<String> impJobs = new ArrayList<String>(); boolean dirs = false; for (File fi : fis) { if (fi.isDirectory()) { dirs = true; File lib = new File(fi, LIBRARY_NAME); if (lib.exists()) { try { Scanner sca = new Scanner(lib); while (sca.hasNextLine()) { String nm = sca.nextLine(); String date = sca.nextLine(); String tags = sca.nextLine(); File addr = new File(fi, nm); if (addr.exists() && !addr.isDirectory()) impJobs.add(impJob(addr, date, tags)); } sca.close(); } catch (IOException exc) { // add nothing? } } else { for (File cont : fi.listFiles()) if (!cont.isDirectory()) impJobs.add(impJob(cont, null, null)); } } else { impJobs.add(impJob(fi, null, null)); } } if (impJobs.size() > 1 || dirs) { // dont bother user if selected single file String shw = "Importing:"; if (impJobs.size() > 30) shw = null; int pcount = 0; for (String jb : impJobs) { String[] prts = jb.split(",", 4); // import jobs have 4 parts, import, name, date, tags if (shw != null) shw = shw + "\n - " + new File(prts[1]).getName(); if (!prts[3].equalsIgnoreCase(Storage.NEW_TAG)) { pcount++; if (shw != null) shw = shw + " []"; } } if (shw == null) shw = "importing "; else shw = shw + "\n"; shw = shw + impJobs.size() + "(" + pcount + ") files"; if (JOptionPane.showConfirmDialog(frm, shw, "Confirm Import", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; } synchronized (jobs) { for (String j : impJobs) { if (priorityExport) jobs.addLast(j); else jobs.addFirst(j); } } updateStatus(); }
public boolean loadSourceFile(File file) { boolean result = false; selectedPath = file.getParent(); BufferedReader sourceFile = null; String directoryPath = file.getParent(); String sourceName = file.getName(); int idx = sourceName.lastIndexOf("."); fileExt = idx == -1 ? "" : sourceName.substring(idx + 1); baseName = idx == -1 ? sourceName.substring(0) : sourceName.substring(0, idx); String basePath = directoryPath + File.separator + baseName; DataOptions.directoryPath = directoryPath; sourcePath = file.getPath(); AssemblerOptions.sourcePath = sourcePath; AssemblerOptions.listingPath = basePath + ".lst"; AssemblerOptions.objectPath = basePath + ".cd"; String var = System.getenv("ROPE_MACROS_DIR"); if (var != null && !var.isEmpty()) { File dir = new File(var); if (dir.exists() && dir.isDirectory()) { AssemblerOptions.macroPath = var; } else { AssemblerOptions.macroPath = directoryPath; } } else { AssemblerOptions.macroPath = directoryPath; } DataOptions.inputPath = AssemblerOptions.objectPath; DataOptions.outputPath = basePath + ".out"; DataOptions.readerPath = null; DataOptions.punchPath = basePath + ".pch"; DataOptions.tape1Path = basePath + ".mt1"; DataOptions.tape2Path = basePath + ".mt2"; DataOptions.tape3Path = basePath + ".mt3"; DataOptions.tape4Path = basePath + ".mt4"; DataOptions.tape5Path = basePath + ".mt5"; DataOptions.tape6Path = basePath + ".mt6"; this.setTitle("EDIT: " + sourceName); fileText.setText(sourcePath); if (dialog == null) { dialog = new AssemblerDialog(mainFrame, "Assembler options"); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension dialogSize = dialog.getSize(); dialog.setLocation( (screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2); } dialog.initialize(); AssemblerOptions.command = dialog.buildCommand(); sourceArea.setText(null); try { sourceFile = new BufferedReader(new FileReader(file)); String line; while ((line = sourceFile.readLine()) != null) { sourceArea.append(line + "\n"); } sourceArea.setCaretPosition(0); optionsButton.setEnabled(true); assembleButton.setEnabled(true); saveButton.setEnabled(true); setSourceChanged(false); undoMgr.discardAllEdits(); result = true; } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (sourceFile != null) { sourceFile.close(); } } catch (IOException ignore) { } } return result; }
public void actionPerformed(ActionEvent e) { if (isDirectorySelected()) { File dir = getDirectory(); if (dir != null) { try { // Strip trailing ".." dir = ShellFolder.getNormalizedFile(dir); } catch (IOException ex) { // Ok, use f as is } changeDirectory(dir); return; } } JFileChooser chooser = getFileChooser(); String filename = getFileName(); FileSystemView fs = chooser.getFileSystemView(); File dir = chooser.getCurrentDirectory(); if (filename != null) { // Remove whitespaces from end of filename int i = filename.length() - 1; while (i >= 0 && filename.charAt(i) <= ' ') { i--; } filename = filename.substring(0, i + 1); } if (filename == null || filename.length() == 0) { // no file selected, multiple selection off, therefore cancel the approve action resetGlobFilter(); return; } File selectedFile = null; File[] selectedFiles = null; // Unix: Resolve '~' to user's home directory if (File.separatorChar == '/') { if (filename.startsWith("~/")) { filename = System.getProperty("user.home") + filename.substring(1); } else if (filename.equals("~")) { filename = System.getProperty("user.home"); } } if (chooser.isMultiSelectionEnabled() && filename.length() > 1 && filename.charAt(0) == '"' && filename.charAt(filename.length() - 1) == '"') { List<File> fList = new ArrayList<File>(); String[] files = filename.substring(1, filename.length() - 1).split("\" \""); // Optimize searching files by names in "children" array Arrays.sort(files); File[] children = null; int childIndex = 0; for (String str : files) { File file = fs.createFileObject(str); if (!file.isAbsolute()) { if (children == null) { children = fs.getFiles(dir, false); Arrays.sort(children); } for (int k = 0; k < children.length; k++) { int l = (childIndex + k) % children.length; if (children[l].getName().equals(str)) { file = children[l]; childIndex = l + 1; break; } } } fList.add(file); } if (!fList.isEmpty()) { selectedFiles = fList.toArray(new File[fList.size()]); } resetGlobFilter(); } else { selectedFile = fs.createFileObject(filename); if (!selectedFile.isAbsolute()) { selectedFile = fs.getChild(dir, filename); } // check for wildcard pattern FileFilter currentFilter = chooser.getFileFilter(); if (!selectedFile.exists() && isGlobPattern(filename)) { changeDirectory(selectedFile.getParentFile()); if (globFilter == null) { globFilter = new GlobFilter(); } try { globFilter.setPattern(selectedFile.getName()); if (!(currentFilter instanceof GlobFilter)) { actualFileFilter = currentFilter; } chooser.setFileFilter(null); chooser.setFileFilter(globFilter); return; } catch (PatternSyntaxException pse) { // Not a valid glob pattern. Abandon filter. } } resetGlobFilter(); // Check for directory change action boolean isDir = (selectedFile != null && selectedFile.isDirectory()); boolean isTrav = (selectedFile != null && chooser.isTraversable(selectedFile)); boolean isDirSelEnabled = chooser.isDirectorySelectionEnabled(); boolean isFileSelEnabled = chooser.isFileSelectionEnabled(); boolean isCtrl = (e != null && (e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0); if (isDir && isTrav && (isCtrl || !isDirSelEnabled)) { changeDirectory(selectedFile); return; } else if ((isDir || !isFileSelEnabled) && (!isDir || !isDirSelEnabled) && (!isDirSelEnabled || selectedFile.exists())) { selectedFile = null; } } if (selectedFiles != null || selectedFile != null) { if (selectedFiles != null || chooser.isMultiSelectionEnabled()) { if (selectedFiles == null) { selectedFiles = new File[] {selectedFile}; } chooser.setSelectedFiles(selectedFiles); // Do it again. This is a fix for bug 4949273 to force the // selected value in case the ListSelectionModel clears it // for non-existing file names. chooser.setSelectedFiles(selectedFiles); } else { chooser.setSelectedFile(selectedFile); } chooser.approveSelection(); } else { if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } chooser.cancelSelection(); } }
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(); } }