// experimental // ==================================================================== // ==================================================================== // ==================================================================== private void readAndDrawBIGGraph(String file) { // behövs inte än // @TODO // hur rita flera linjer mellan 2 noder? (för flera linjer) // reading of the graph should be done in the graph itself // it should be possible to get an iterator over nodes and one over edges // read in all the stops and lines and draw the lmap Scanner indata = null; // insert into p-queue to get them sorted names = new PriorityQueue<String>(); try { // Read stops and put them in the node-table // in order to give the user a list of possible stops // assume input file is correct indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); // while (indata.hasNext()) { String hpl = indata.next().trim(); int xco = indata.nextInt(); int yco = indata.nextInt(); noderna.add(new BusStop(hpl, xco, yco)); names.add(hpl); // Draw // this is a fix: fixa att Kålltorp och Torp är samma hållplats if (hpl.equals("Torp")) { xco += 11; hpl = " / Torp"; } karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE); } indata.close(); // Read in the lines and add to the graph indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859"); grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes()); Color color = new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); // String lineNo = "1"; // while (indata.hasNext()) { // assume lines are correct int from = noderna.find(indata.next()).getNodeNo(); int to = noderna.find(indata.next()).getNodeNo(); grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo)); indata.nextLine(); // skip rest of line // Draw BusStop busFrom = noderna.find(from); BusStop busTo = noderna.find(to); karta.drawLine( busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE); } indata.close(); } catch (FileNotFoundException fnfe) { throw new RuntimeException(" Indata till busshållplatserna saknas"); } karta.repaint(); } // end readAndDrawBIGGraph
/** * Opens a file. If the file can be opened, get a drawing time estimate, update recent files list, * and repaint the preview tab. * * @param filename what file to open */ public void LoadGCode(String filename) { CloseFile(); try { Scanner scanner = new Scanner(new FileInputStream(filename)); linesTotal = 0; gcode = new ArrayList<String>(); try { while (scanner.hasNextLine()) { gcode.add(scanner.nextLine()); ++linesTotal; } } finally { scanner.close(); } } catch (IOException e) { Log("<span style='color:red'>File could not be opened.</span>\n"); RemoveRecentFile(filename); return; } previewPane.setGCode(gcode); fileOpened = true; EstimateDrawTime(); UpdateRecentFiles(filename); Halt(); }
public void readFile() throws IOException, FileNotFoundException { Scanner inp = new Scanner(System.in); System.out.print("Enter the name of the file to process: "); String file; file = inp.nextLine(); System.out.println(file); Scanner fileScan = new Scanner(new FileReader(file)); fileScan.useDelimiter(","); numBars = fileScan.nextInt(); values = new int[numBars]; labels = new String[numBars]; for (int i = 0; i < numBars - 1; i++) { values[i] = fileScan.nextInt(); labels[i] = fileScan.next(); System.out.println(values[i] + " " + labels[i]); } inp.close(); fileScan.close(); }
/** Display the file in the text area */ private void showFile() { Scanner input = null; try { // Use a Scanner to read text from the file input = new Scanner(new File(jtfFilename.getText().trim())); // Read a line and append the line to the text area while (input.hasNext()) jtaFile.append(input.nextLine() + '\n'); } catch (FileNotFoundException ex) { System.out.println("File not found: " + jtfFilename.getText()); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) input.close(); } }
// Constructor public Ballot(int index, int ID, int numCandidates, String title, ArrayList<String> candidates) throws IOException { _index = index; _ID = ID; _numCandidates = numCandidates; _votes = new int[_numCandidates]; _title = title; _candidates = candidates; _usrVotes = new String[numCandidates]; // if the ballot file already exists, read in the votes for that ballot // otherwise the number of votes for each candidate will default to 0 file = new File(_ID + ".txt"); if (file.exists()) { Scanner reader = new Scanner(file); int i = 0; while (reader.hasNextLine()) { String strLine = reader.nextLine(); String arrLine[] = strLine.split(":"); int vote = Integer.parseInt(arrLine[1]); _votes[i] = vote; i++; } reader.close(); } _ballotPanel = new JPanel(); _ballotPanel.setLayout(new GridLayout(_candidates.size() + 1, 1)); _titleLabel = new JLabel(_title); _titleLabel.setHorizontalAlignment(JLabel.CENTER); _titleLabel.setFont(new Font("CourierNew", Font.PLAIN, 15)); _ballotPanel.add(_titleLabel); for (int i = 0; i < _candidates.size(); i++) { // Make a JButton for each candidate in the ballot // Disable it by default. Will enable when the user logs in String cText = _candidates.get(i); JButton candidate = new JButton(cText); candidate.setEnabled(false); candidate.addActionListener(_buttonListener); _candidateButtons.add(candidate); _ballotPanel.add(candidate); } }
public TreeViewer(String title, int ulx, int uly, int pw, int ph) { super(title, ulx, uly, pw, ph); // code to initialize instance variables before animation begins: // ------------------------------------------------------------------ state = "regular"; spread = 1; levelHeight = 10; // 10 levels for the camera region height tree = new SackBST(); String fileName = FileBrowser.chooseFile(true); try { Scanner input = new Scanner(new File(fileName)); String s; while (input.hasNext()) { s = input.nextLine(); if (s != null) { tree.add(s); } } input.close(); } catch (Exception e) { System.out.println("File load failed"); System.exit(1); } // code to finish setting up entire window: // ------------------------------------------------------------------ setBackgroundColor(new Color(128, 128, 200)); // code to set up camera(s) // ------------------------------------------------------------------ cameras.add(new Camera(10, 50, camw, camh, 0, 100, 0, new Color(255, 200, 255))); cameras.add(new Camera(10, 50 + camh + 10, camw, 20, 0, 100, 0, new Color(255, 255, 255))); // ------------------------------------------------------------------ // start up the animation: super.start(); }
public void fileScan(String filename) throws IOException { Scanner sf = new Scanner(new File(filename)); int maxIndex = -1; String s = ""; while (sf.hasNext()) { maxIndex++; s = sf.nextLine(); dtr[maxIndex] = s; odtr[maxIndex] = s; s = sf.nextLine(); d1[maxIndex] = s; od1[maxIndex] = s; d2[maxIndex] = sf.nextLine(); d3[maxIndex] = sf.nextLine(); d4[maxIndex] = sf.nextLine(); } sf.close(); }
/** * Makes a POST request and returns the server response. * * @param urlString the URL to post to * @param nameValuePairs a map of name/value pairs to supply in the request. * @return the server reply (either from the input stream or the error stream) */ public static String doPost(String urlString, Map<String, String> nameValuePairs) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) { if (first) first = false; else out.print('&'); String name = pair.getKey(); String value = pair.getValue(); out.print(name); out.print('='); out.print(URLEncoder.encode(value, "UTF-8")); } out.close(); Scanner in; StringBuilder response = new StringBuilder(); try { in = new Scanner(connection.getInputStream()); } catch (IOException e) { if (!(connection instanceof HttpURLConnection)) throw e; InputStream err = ((HttpURLConnection) connection).getErrorStream(); if (err == null) throw e; in = new Scanner(err); } while (in.hasNextLine()) { response.append(in.nextLine()); response.append("\n"); } in.close(); return response.toString(); }
private String getFileWords(String s) { String output = ""; try { // THIS CODE SEGMENT WILL NOT RUN IN AN APPLET THAT IS NOT "SIGNED" // By default applets cannot alter files on the hard drive of the user. // If the panel is opened in a regular application the save button should work. // This can be tested in HomeworkApplication.java through HomeworkRun.java only File inputFile = new File(s); Scanner inputScanner = new Scanner(inputFile); while (inputScanner.hasNext()) { output = output + inputScanner.nextLine() + "\n"; } inputScanner.close(); String numWords = getWords(output); return numWords; } catch (IOException e) { outputLabel.append(e + ""); } return output; }
private void insertRows(Connection connection) { // Build the SQL INSERT statement String sqlInsert = "insert into " + jtfTableName.getText() + " values ("; // Use a Scanner to read text from the file Scanner input = null; // Get file name from the text field String filename = jtfFilename.getText().trim(); try { // Create a scanner input = new Scanner(new File(filename)); // Create a statement Statement statement = connection.createStatement(); System.out.println( "Driver major version? " + connection.getMetaData().getDriverMajorVersion()); // Determine if batchUpdatesSupported is supported boolean batchUpdatesSupported = false; try { if (connection.getMetaData().supportsBatchUpdates()) { batchUpdatesSupported = true; System.out.println("batch updates supported"); } else { System.out.println( "The driver is of JDBC 2 type, but " + "does not support batch updates"); } } catch (UnsupportedOperationException ex) { System.out.println("The driver does not support JDBC 2"); } // Determine if the driver is capable of batch updates if (batchUpdatesSupported) { // Read a line and add the insert table command to the batch while (input.hasNext()) { statement.addBatch(sqlInsert + input.nextLine() + ")"); } statement.executeBatch(); jlblStatus.setText("Batch updates completed"); } else { // Read a line and execute insert table command while (input.hasNext()) { statement.executeUpdate(sqlInsert + input.nextLine() + ")"); } jlblStatus.setText("Single row update completed"); } } catch (SQLException ex) { System.out.println(ex); } catch (FileNotFoundException ex) { System.out.println("File not found: " + filename); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) input.close(); } }
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(); }
@Override public void actionPerformed(ActionEvent action) { // Get the file the user wants to use and store it. if (action.getSource() == chooseFile) { // *sigh* I spent like 10 minutes trying to figure out why my if statement was not working // and then I found a semicolon on the end...noob mistake... // I had written a paragraph about it to send you too. if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { try { System.out.println( "File: " + fileChooser.getSelectedFile() + "\nInt: " + fileChooser.showOpenDialog(this)); file = fileChooser.getSelectedFile(); inputFile = new Scanner(file); if (JOptionPane.showConfirmDialog( this, "Overwrite orginal file?", "Overwrite Confimration", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { outputFile = new PrintWriter(file); } else { fileChooser.showOpenDialog(this); outputFile = new PrintWriter(fileChooser.getSelectedFile()); } // Enable the buttons now that a file has been chosen. sort.setEnabled(true); next.setEnabled(true); } catch (FileNotFoundException exception) { JOptionPane.showMessageDialog(this, "Error: Could not find or open file."); exception.printStackTrace(); } // Just in case something weird happens and all those files don't get linked correctly, // this will get called and prevent the buttons from being enabled. Essentially, the user // won't see anything. catch (NullPointerException exception) { sort.setEnabled(false); next.setEnabled(false); exception.printStackTrace(); } } } else if (action.getSource() == sort) { // Call the quicksort method to sort, and handle the file writing. while (inputFile.hasNextLine()) { arrayList.add(inputFile.nextLine()); } inputFile.close(); temp = new String[arrayList.size()]; array = arrayList.toArray(temp); sorter.quicksort(array, 0, array.length - 1); for (int i = 0; i < array.length; i++) { outputFile.println(array[i]); } outputFile.close(); JOptionPane.showMessageDialog(this, "List successfully sorted."); } else if (action.getSource() == next) { // Go to the search options. buttonPanel.remove(chooseFile); buttonPanel.remove(sort); buttonPanel.add(search); repaint(); setVisible(true); } else if (action.getSource() == exit) { // Exit, obviously. dispose(); } else if (action.getSource() == search) { // Call the binarySearch method and display the result. String searchValue = JOptionPane.showInputDialog("Enter the value to search for:"); boolean ignoreCase; int result; if (JOptionPane.showConfirmDialog( this, "Case-sensitive search?", "Case-sensitive", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { ignoreCase = false; } else { ignoreCase = true; } result = searcher.binarySearch(array, searchValue, ignoreCase) + 1; if (result == 0) { text.setText("The value, " + searchValue + ", was not found."); } else { text.setText("The value, " + searchValue + ", was found on line: " + result + "."); } } }
// ==================================================================== // ==================================================================== private void readAndDrawGraph() { // @TODO // hur rita flera linjer mellan 2 noder? (för flera linjer) // reading of the graph should be done in the graph itself // it should be possible to get an iterator over nodes and one over edges // read in all the stops and lines and draw the lmap Scanner indata = null; // insert into p-queue to get them sorted names = new PriorityQueue<String>(); try { // Read stops and put them in the node-table // in order to give the user a list of possible stops // assume input file is correct indata = new Scanner(new File("stops.noBOM.txt"), "UTF-8"); while (indata.hasNext()) { String hpl = indata.next().trim(); int xco = indata.nextInt(); int yco = indata.nextInt(); noderna.add(new BusStop(hpl, xco, yco)); names.add(hpl); // Draw /* // Denna fix som slår ihop Kålltorp och Torp är förvirrande eftersom de är olika noder i grafen. // Tror man att det är samma nod blir resultatet förrvirrande. // Till nästa gång: Gör till samma nod med namnet Virginsgatan. Så är det i verkligheten nu. // this is a fix: fixa att Kålltorp och Torp är samma hållplats if ( hpl.equals("Torp") ) { xco += 11; hpl = " / Torp"; } */ karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE); } indata.close(); // Read in the lines and add to the graph indata = new Scanner(new File("lines.noBOM.txt"), "UTF-8"); grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes()); while (indata.hasNext()) { String lineNo = indata.next(); int antal = indata.nextInt() - 1; int from = noderna.find(indata.next()).getNodeNo(); // hur rita flera linjer mellan 2 noder? // enkel inc fungerar inte // färgen kunde vara "äkta" dvs linjefärg Color color = new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); for (int i = 0; i < antal; i++) { int to = noderna.find(indata.next()).getNodeNo(); grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo)); // Draw BusStop busFrom = noderna.find(from); BusStop busTo = noderna.find(to); karta.drawLine( busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE); from = to; } } indata.close(); } catch (FileNotFoundException fnfe) { throw new RuntimeException(" Indata till busshållplatserna saknas"); } karta.repaint(); } // end readAndDrawGraph