private void saveCurrent() { PrintWriter writer = null; try { writer = new PrintWriter("config.txt", "UTF-8"); writer.println("PhoneNumbers:"); for (String s : Main.getEmails()) { writer.println(s); } writer.println("Items:"); for (Item s : Main.getItems()) { writer.println(s.getName() + "," + s.getWebsite()); } results.setText("Current settings have been saved sucessfully."); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } writer.close(); }
private void onOK() { // add your code here try { PrintWriter pw = new PrintWriter("data\\out.txt"); pw.println(textField1.getText()); pw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
private Scanner scanFile() { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("./lab3/Liv.xml"))); s.nextLine(); } catch (FileNotFoundException e) { e.printStackTrace(); } return s; }
private OutputStream createFile(String fileName) { OutputStream outputStream = null; File outputFile = new File(fileName); try { outputStream = new FileOutputStream(outputFile); } catch (FileNotFoundException e) { e.printStackTrace(); } return outputStream; }
public Class loadNewClass(String javaFile, String packageName) { Class myClass = null; String className = javaFile.replace(".java", ".class"); File inpFile = new File(className); int idx = className.lastIndexOf(File.separatorChar); String javaName = className.substring(idx + 1, className.indexOf(".")); int size = (int) inpFile.length(); byte[] ba = new byte[size]; try { FileInputStream fis = new FileInputStream(className); // read the entry int bytes_read = 0; while (bytes_read != size) { int r = fis.read(ba, bytes_read, size - bytes_read); if (r < 0) break; bytes_read += r; } if (bytes_read != size) throw new IOException("cannot read entry"); } catch (FileNotFoundException fnfExc) { System.out.println("File : " + className + " not found"); fnfExc.printStackTrace(); } catch (IOException ioExc) { System.out.println("IO Exception in JavaCompile trying to read class: "); ioExc.printStackTrace(); } try { String packageAppendedFileName = ""; if (packageName.isEmpty()) packageAppendedFileName = javaName; else packageAppendedFileName = packageName + "." + javaName; packageAppendedFileName.replace(File.separatorChar, '.'); myClass = defineClass(packageAppendedFileName, ba, 0, size); // SOS-StergAutoCompletionScalaSci.upDateAutoCompletion(myClass); String userClassName = myClass.getName(); JOptionPane.showMessageDialog(null, "Class " + userClassName + " loaded successfully !"); } catch (ClassFormatError exc) { System.out.println("error defining class " + inpFile); exc.printStackTrace(); } catch (Exception ex) { System.out.println("some error defining class " + inpFile); ex.printStackTrace(); } return myClass; }
/** * Opens an InputStream. * * @return the stream */ public InputStream openInputStream() { if (getFile() != null) { try { return new FileInputStream(getFile()); } catch (FileNotFoundException ex) { ex.printStackTrace(); } } if (getURL() != null) { try { return getURL().openStream(); } catch (IOException ex) { ex.printStackTrace(); } } return null; }
/** Sets some ui properties and loads oroperties from .whatswrong */ static { System.setProperty("apple.laf.useScreenMenuBar", "true"); try { File file = new File(System.getProperty("user.home") + "/.whatswrong"); if (file.exists()) { properties.load(new FileInputStream(file)); } else { properties.setProperty("whatswrong.golddir", System.getProperty("user.dir")); properties.setProperty("whatswrong.guessdir", System.getProperty("user.dir")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public Vector<Integer> getHighScore(String chemin) { BufferedReader reader; Vector<Integer> highScores = new Vector<Integer>(); try { reader = new BufferedReader(new FileReader(new File(chemin))); do { highScores.add(Integer.parseInt(reader.readLine())); } while (reader != null); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NumberFormatException e) { } return highScores; }
/** * The main method. * * @param args the arguments */ public static void main(String[] args) { Questionnaire quiz = new Questionnaire(); try { quiz.initQuestionnaire("question_tolkien.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } new QuestionnaireUI(quiz); }
public static void music(char gameResult) { AudioPlayer MGP = AudioPlayer.player; AudioStream BGM, BGM1; AudioData MD; ContinuousAudioDataStream loop = null; try { InputStream winAudio = new FileInputStream("Audio/winrevised.wav"); InputStream loseAudio = new FileInputStream("Audio/loserevised.wav"); BGM = new AudioStream(winAudio); BGM1 = new AudioStream(loseAudio); if (gameResult == 'w') AudioPlayer.player.start(BGM); else if (gameResult == 'l') AudioPlayer.player.start(BGM1); // MD = BGM.getData(); // loop = new ContinuousAudioDataStream(MD); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException error) { error.printStackTrace(); } MGP.start(loop); }
public static void main(String[] args) { // read filename and N 2 parameters String fileName = args[0]; N = Integer.parseInt(args[1]); // output two images, one original image at left, the other result image at right BufferedImage imgOriginal = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); BufferedImage img = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB); try { File file = new File(fileName); InputStream is = new FileInputStream(file); long len = file.length(); byte[] bytes = new byte[(int) len]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } int ind = 0; for (int y = 0; y < IMAGE_HEIGHT; y++) { for (int x = 0; x < IMAGE_WIDTH; x++) { // for reading .raw image to show as a rgb image byte r = bytes[ind]; byte g = bytes[ind]; byte b = bytes[ind]; // set pixel for display original image int pixOriginal = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff); imgOriginal.setRGB(x, y, pixOriginal); ind++; } } is.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int[] vectorSpace = calculateVectorSpace(imgOriginal); // quantization for (int y = 0; y < IMAGE_HEIGHT; y++) { for (int x = 0; x < IMAGE_WIDTH; x++) { int clusterId = vectorSpace[IMAGE_WIDTH * y + x]; img.setRGB(x, y, clusters[clusterId].getPixel()); } } // Use a panel and label to display the image JPanel panel = new JPanel(); panel.add(new JLabel(new ImageIcon(imgOriginal))); panel.add(new JLabel(new ImageIcon(img))); JFrame frame = new JFrame("Display images"); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
private void savePhone() { if (phone.getText().length() == 10) { File f = new File("config.txt"); Scanner sc; ArrayList<String> config = new ArrayList<String>(); try { sc = new Scanner(f); while (sc.hasNext()) { String s = sc.nextLine(); config.add(s); } sc.close(); } catch (FileNotFoundException e2) { results.setText("Error reading config.txt"); } int i = 0; for (String s : config) { if (s.equals("PhoneNumbers:")) { break; } i++; } if (carriers.getSelectedIndex() == 0) { config.add(i + 1, phone.getText() + "@txt.att.net"); } if (carriers.getSelectedIndex() == 1) { config.add(i + 1, phone.getText() + "@myboostmobile.com"); } if (carriers.getSelectedIndex() == 2) { config.add(i + 1, phone.getText() + "@mobile.celloneusa.com"); } if (carriers.getSelectedIndex() == 3) { config.add(i + 1, phone.getText() + "@messaging.nextel.com"); } if (carriers.getSelectedIndex() == 4) { config.add(i + 1, phone.getText() + "@tmomail.net"); } if (carriers.getSelectedIndex() == 5) { config.add(i + 1, phone.getText() + "@txt.att.net"); } if (carriers.getSelectedIndex() == 6) { config.add(i + 1, phone.getText() + "@email.uscc.net"); } if (carriers.getSelectedIndex() == 7) { config.add(i + 1, phone.getText() + "@messaging.sprintpcs.com"); } if (carriers.getSelectedIndex() == 8) { config.add(i + 1, phone.getText() + "@vtext.com"); } if (carriers.getSelectedIndex() == 9) { config.add(i + 1, phone.getText() + "@vmobl.com"); } PrintWriter writer = null; try { writer = new PrintWriter("config.txt", "UTF-8"); for (String s : config) { writer.println(s); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } writer.close(); addPhone(); } else { results.setText("Please add 10 digit cell number."); } }
@Override public void run() { final int maxAllowedExceptions = 5; int catchedExceptions = 0; while (true) { try { // if there is no work in queue this call waits for a new queue item final ModelItem<?> item = directTransferQueue.getItemFromQueue(); if (item == null) { // paranoia, should never happen Mixed.wait(5 * 1000); continue; } if (item instanceof FrostUploadItem) { // transfer bytes to node final FrostUploadItem ulItem = (FrostUploadItem) item; // FIXME: provide item, state=Transfer to node, % shows progress final String gqid = ulItem.getGqIdentifier(); final boolean doMime; final boolean setTargetFileName; if (ulItem.isSharedFile()) { doMime = false; setTargetFileName = false; } else { doMime = true; setTargetFileName = true; } final NodeMessage answer = fcpTools.startDirectPersistentPut( gqid, ulItem.getFile(), ulItem.getFileName(), doMime, setTargetFileName, ulItem.getCompress(), ulItem.getFreenetCompatibilityMode(), ulItem.getPriority()); if (answer == null) { final String desc = "Could not open a new FCP2 socket for direct put!"; final FcpResultPut result = new FcpResultPut(FcpResultPut.Error, -1, desc, false); FileTransferManager.inst().getUploadManager().notifyUploadFinished(ulItem, result); logger.severe(desc); } else { // wait for an answer, don't start request again directPUTsWithoutAnswer.add(gqid); } directPUTsInProgress.remove(gqid); } else if (item instanceof FrostDownloadItem) { // transfer bytes from node final FrostDownloadItem dlItem = (FrostDownloadItem) item; // FIXME: provide item, state=Transfer from node, % shows progress final String gqid = dlItem.getGqIdentifier(); final File targetFile = new File(dlItem.getDownloadFilename()); final boolean retryNow; NodeMessage answer = null; try { answer = fcpTools.startDirectPersistentGet(gqid, targetFile); } catch (final FileNotFoundException e) { final String msg = "Could not write to " + dlItem.getDownloadFilename() + ": " + e.getMessage(); System.out.println(msg); logger.severe(msg); } if (answer != null) { final FcpResultGet result = new FcpResultGet(true); FileTransferManager.inst() .getDownloadManager() .notifyDownloadFinished(dlItem, result, targetFile); retryNow = false; } else { logger.severe("Could not open a new fcp socket for direct get!"); final FcpResultGet result = new FcpResultGet(false); retryNow = FileTransferManager.inst() .getDownloadManager() .notifyDownloadFinished(dlItem, result, targetFile); } directGETsInProgress.remove(gqid); if (retryNow) { startDownload(dlItem); } } } catch (final Throwable t) { logger.log(Level.SEVERE, "Exception catched", t); catchedExceptions++; } if (catchedExceptions > maxAllowedExceptions) { logger.log(Level.SEVERE, "Stopping DirectTransferThread because of too much exceptions"); break; } } }
@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 doSave() { myFile = doRead(); if (myFile == null) { return; } String name = myFile.getName(); showMessage("compressing " + name); String newName = JOptionPane.showInputDialog(this, "Name of compressed file", name + HUFF_SUFFIX); if (newName == null) { return; } String path = null; try { path = myFile.getCanonicalPath(); } catch (IOException e) { showError("trouble with file canonicalizing"); return; } int pos = path.lastIndexOf(name); newName = path.substring(0, pos) + newName; final File file = new File(newName); try { final FileOutputStream out = new FileOutputStream(file); ProgressMonitorInputStream temp = null; if (myFast) { temp = getMonitorableStream(getFastByteReader(myFile), "compressing bits..."); } else { temp = getMonitorableStream(myFile, "compressing bits ..."); } final ProgressMonitorInputStream pmis = temp; final ProgressMonitor progress = pmis.getProgressMonitor(); Thread fileWriterThread = new Thread() { public void run() { try { while (!myFirstReadingDone) { try { sleep(100); } catch (InterruptedException e) { // what to do? HuffViewer.this.showError("Trouble in Thread " + e); } } myModel.compress(pmis, out, myForce); } catch (IOException e) { HuffViewer.this.showError("compression exception\n " + e); cleanUp(file); // e.printStackTrace(); } if (progress.isCanceled()) { HuffViewer.this.showError("compression cancelled"); cleanUp(file); } } }; fileWriterThread.start(); } catch (FileNotFoundException e) { showError("could not open " + file.getName()); e.printStackTrace(); } myFile = null; }
private void doDecode() { File file = null; showMessage("uncompressing"); try { int retval = ourChooser.showOpenDialog(null); if (retval != JFileChooser.APPROVE_OPTION) { return; } file = ourChooser.getSelectedFile(); String name = file.getName(); String uname = name; if (name.endsWith(HUFF_SUFFIX)) { uname = name.substring(0, name.length() - HUFF_SUFFIX.length()) + UNHUFF_SUFFIX; } else { uname = name + UNHUFF_SUFFIX; } String newName = JOptionPane.showInputDialog(this, "Name of uncompressed file", uname); if (newName == null) { return; } String path = file.getCanonicalPath(); int pos = path.lastIndexOf(name); newName = path.substring(0, pos) + newName; final File newFile = new File(newName); ProgressMonitorInputStream temp = null; if (myFast) { temp = getMonitorableStream(getFastByteReader(file), "uncompressing bits ..."); } else { temp = getMonitorableStream(file, "uncompressing bits..."); } final ProgressMonitorInputStream stream = temp; final ProgressMonitor progress = stream.getProgressMonitor(); final OutputStream out = new FileOutputStream(newFile); Thread fileReaderThread = new Thread() { public void run() { try { myModel.uncompress(stream, out); } catch (IOException e) { cleanUp(newFile); HuffViewer.this.showError("could not uncompress\n " + e); // e.printStackTrace(); } if (progress.isCanceled()) { cleanUp(newFile); HuffViewer.this.showError("reading cancelled"); } } }; fileReaderThread.start(); } catch (FileNotFoundException e) { showError("could not open " + file.getName()); e.printStackTrace(); } catch (IOException e) { showError("IOException, uncompression halted from viewer"); e.printStackTrace(); } }
// Thread's run method aimed at creating a bitmap asynchronously public void run() { Drawing drawing = new Drawing(); PicText rawPicText = new PicText(); String s = ((PicText) element).getText(); rawPicText.setText(s); drawing.add( rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former // parent... (then pb with the view ) drawing.setNotparsedCommands( "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{" + s + "}" + CR_LF + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{" + s + "}" + CR_LF + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{" + s + "}" + CR_LF + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight, \\the\\jpicdepth }" + CR_LF); RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION; // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun); boolean isWriteTmpTeXfile = true; String bitmapExt = "png"; // [pending] preferences String cmdLine = "{i}/unix/tetex/create_bitmap.sh {p} {f} " + bitmapExt + " " + fileDPI; // [pending] preferences ContentType contentType = getContainer().getContentType(); RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug RunExternalCommand command = new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile); command .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX // process has completed) if (wantToComputeLatexDimensions) { // load size of text: try { File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); } catch (FileNotFoundException fnfe) { System.out.println("Cannot find log file! " + fnfe.getMessage()); System.out.println(logFile); } catch (IOException ioex) { System.out.println("Log file IO exception"); ioex.printStackTrace(); } // utile ? System.out.println("Log file created! file=" + logFile); getDimensionsFromLogFile(reader, (PicText) element); syncStringLocation(); // update dimensions syncBounds(); syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that dimensions are available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } if (wantToGetBitMap) { // load image: try { File bitmapFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt); this.image = ImageIO.read(bitmapFile); System.out.println( "Bitmap created! file=" + bitmapFile + ", width=" + image.getWidth() + "pixels, height=" + image.getHeight() + "pixels"); if (image == null) return; syncStringLocation(); // sets strx, stry, and dimensions of text syncBounds(); // update the AffineTransform that will be applied to the bitmap before displaying on screen PicText te = (PicText) element; text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! text2ModelTr.translate(te.getLeftX(), te.getTopY()); text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); // [pending] should do something special to avoid dividing by 0 or setting a rescaling // factor to 0 [non invertible matrix] (java will throw an exception) syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that bitmap is available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } }
public void jFileChooserActionPerformed(java.awt.event.ActionEvent evt) throws FileNotFoundException, IOException { File initialBoard = this.jFileChooser.getSelectedFile(); InputStream inputStream = new FileInputStream(initialBoard); Scanner scanner = new Scanner(inputStream); if (!initialBoard .getName() .toLowerCase() .contains("initialboard")) { // .toLowerCase().compareTo("initialboard")!=0){ JOptionPane.showMessageDialog( frame, "Wrong File \n Please select InitialBoard.txt", "Eror", JOptionPane.ERROR_MESSAGE); } else { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { in = new BufferedReader(new FileReader(initialBoard.getAbsolutePath())); } catch (FileNotFoundException e) { System.out.println(e.getCause()); System.out.println("Error loading initial board"); } int[] boardRows = new int[15]; // ---------------- String text = in.readLine(); StringTokenizer tokenizer = new StringTokenizer(text, " "); int boardSize = 0; while (tokenizer.hasMoreElements()) { boardRows[boardSize] = Integer.parseInt(tokenizer.nextToken()); boardSize++; } int[] newBoard = new int[boardSize * boardSize + 1]; System.arraycopy(boardRows, 0, newBoard, 1, boardSize); int index = 0; while (in.ready()) { index++; text = in.readLine(); tokenizer = new StringTokenizer(text, " "); int pos = 0; while (tokenizer.hasMoreElements()) { pos++; newBoard[index * boardSize + pos] = Integer.parseInt(tokenizer.nextToken()); } } this.jFrameFileChooser.setVisible(false); // this.boardPanel.s gameInitialBoard = new Board(newBoard, boardSize); gameBoard = new Board(newBoard, boardSize); init(); } }