Exemplo n.º 1
1
  // --------------------------------actionConnect------------------------------
  private void actionConnect() {
    if (oParty == null) {
      JOptionPane.showMessageDialog(frame, "Make a party before trying to connect.");
      return;
    }

    String[] oResults = (String[]) DialogManager.show(DialogManager.CONNECT, frame);

    if (oResults[DialogManager.RETURN_IP].equals("cancel")) return;

    lblStatus3.setText("Connecting...");
    try {
      oConn.connect(
          oResults[DialogManager.RETURN_IP], Integer.parseInt(oResults[DialogManager.RETURN_PORT]));
    } catch (UnknownHostException e) {
      JOptionPane.showMessageDialog(
          frame,
          "The IP of the host cannot be determined.",
          "Unknown Host Exception",
          JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    } catch (IOException e) {
      JOptionPane.showMessageDialog(
          frame, e.getMessage(), "Input/Output Exception", JOptionPane.ERROR_MESSAGE);
      frame.repaint();
      return;
    }
    echo("Connected to opponent!");

    tConn = new Thread(oConn, "conn");
    tConn.start();
    tMain = new Thread(this, "main");
    tMain.start();
  }
Exemplo n.º 2
0
  /**
   * 向服务器发送命令行,给服务器端处理
   *
   * @param lines 命令行
   */
  public static void clientSend(String[] lines) {
    if (lines != null && lines.length <= 0) {
      return;
    }
    Socket socket = null;
    PrintWriter writer = null;
    try {
      socket = new Socket("localhost", port);

      writer =
          new PrintWriter(
              new BufferedWriter(
                  new OutputStreamWriter(
                      socket.getOutputStream(), EncodeConstants.ENCODING_UTF_8)));
      for (int i = 0; i < lines.length; i++) {
        writer.println(lines[i]);
      }

      writer.flush();
    } catch (Exception e) {
      FRContext.getLogger().error(e.getMessage(), e);
    } finally {
      try {
        writer.close();
        socket.close();
      } catch (IOException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
  }
Exemplo n.º 3
0
  void lookUpTaxonID(String taxonID) {
    URI url;

    try {
      // We should look up the miITIS_TSN status, but since we don't
      // have any options there ...
      url =
          new URI(
              "http://www.itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value="
                  + taxonID);
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }

    try {
      Desktop desktop = Desktop.getDesktop();
      desktop.browse(url);

    } catch (IOException e) {
      MessageBox.messageBox(
          mainFrame,
          "Could not open URL '" + url + "'",
          "The following error occurred while looking up URL '" + url + "': " + e.getMessage(),
          MessageBox.ERROR);
    }
  }
Exemplo n.º 4
0
  /**
   * Repeats the capture with the current settings.
   *
   * @param aParent the parent window to use, can be <code>null</code>.
   */
  public boolean repeatCaptureData(final Window aParent) {
    final DeviceController devCtrl = getDeviceController();
    if (devCtrl == null) {
      return false;
    }

    try {
      setStatus(
          "Capture from {0} started at {1,date,medium} {1,time,medium} ...",
          devCtrl.getName(), new Date());

      devCtrl.captureData(this);

      return true;
    } catch (IOException exception) {
      captureAborted("I/O problem: " + exception.getMessage());

      exception.printStackTrace();

      // Make sure to handle IO-interrupted exceptions properly!
      HostUtils.handleInterruptedException(exception);

      return false;
    } finally {
      updateActions();
    }
  }
Exemplo n.º 5
0
  public synchronized void run() {

    byte[] buffer = new byte[BUFFER_SIZE];

    for (; ; ) {
      try {
        this.wait(100);
      } catch (InterruptedException ie) {
      }

      int len = 0;
      try {
        int noBytes = pin.available();

        if (noBytes > 0) {
          len = pin.read(buffer, 0, Math.min(noBytes, BUFFER_SIZE));
          if (len > 0) {
            jTextArea.append(new String(buffer, 0, len));
            jTextArea.setCaretPosition(jTextArea.getText().length());
          }
        }
      } catch (IOException ioe) {
        throw new UIError("Unable to read from input stream! " + ioe.getMessage());
      }
    }
  }
Exemplo n.º 6
0
  public void lire() {
    int x = 0;
    try {
      File f = new File(_cheminInit);
      FileReader fr = new FileReader(f);
      BufferedReader br = new BufferedReader(fr);
      try {
        // initialisation
        String line = br.readLine();
        _poids = Double.parseDouble(line) * 9.81;
        line = br.readLine();
        _pasTemps = Double.parseDouble(line);

        line = br.readLine();
        while (line != null) {
          _tabDonnee.add(Double.parseDouble(line));
          ++x;
          line = br.readLine();
        }
        br.close();
        fr.close();
      } catch (IOException exception) {
        System.out.println("Erreur : " + exception.getMessage());
      }
    } catch (FileNotFoundException exception) {
      System.out.println("Erreur : Fichier non trouvé");
    }
  }
Exemplo n.º 7
0
  boolean doSaveNcml(String text, String filename) {
    if (debugNcmlWrite) {
      System.out.println("filename=" + filename);
      System.out.println("text=" + text);
    }

    File out = new File(filename);
    if (out.exists()) {
      int val =
          JOptionPane.showConfirmDialog(
              null,
              filename + " already exists. Do you want to overwrite?",
              "WARNING",
              JOptionPane.YES_NO_OPTION);
      if (val != JOptionPane.YES_OPTION) return false;
    }

    try {
      IO.writeToFile(text, out);
      JOptionPane.showMessageDialog(this, "File successfully written");
      return true;
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage());
      ioe.printStackTrace();
      return false;
    }
    // saveNcmlDialog.setVisible(false);
  }
Exemplo n.º 8
0
  private boolean connectSPPMon() {
    if (state == ConnectionEvent.CONNECTION_PENDING) {
      ExpCoordinator.print(
          new String("NCCPConnection(" + host + ", " + port + ").connect connection pending"), 0);
      while (state == ConnectionEvent.CONNECTION_PENDING) {
        try {
          Thread.sleep(500);
        } catch (java.lang.InterruptedException e) {
        }
      }
      return (isConnected());
    }

    state = ConnectionEvent.CONNECTION_PENDING;
    if (nonProxy != null) {
      try {
        nonProxy.connect();
      } catch (UnknownHostException e) {
        boolean rtn = informUserError("Don't know about host: " + host + ":" + e.getMessage());
        return rtn;
      } catch (SocketTimeoutException e) {
        boolean rtn = informUserError("Socket time out for " + host + ":" + e.getMessage());
        return rtn;
      } catch (IOException e) {
        boolean rtn = informUserError("Couldnt get I/O for " + host + ":" + e.getMessage());
        return rtn;
      }
    }
    return (isConnected());
  }
Exemplo n.º 9
0
  void searchName(String nameToMatch) {
    URI url;

    try {
      // We should look up the miITIS_TSN status, but since we don't
      // have any options there ...
      url = new URI("http", "www.google.com", "/search", "q=" + nameToMatch);
      // I think the URI handles the URL encoding?

    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }

    try {
      Desktop desktop = Desktop.getDesktop();
      desktop.browse(url);

    } catch (IOException e) {
      MessageBox.messageBox(
          mainFrame,
          "Could not open URL '" + url + "'",
          "The following error occurred while looking up URL '" + url + "': " + e.getMessage(),
          MessageBox.ERROR);
    }
  }
 public static void writeArray(String s, int[] x) {
   try {
     RandomAccessFile output = new RandomAccessFile(s, "rw");
     for (int i = 0; i < x.length; i++) output.writeInt(x[i]);
   } catch (IOException e) {
     System.out.println(e.getMessage());
   }
 }
Exemplo n.º 11
0
 public String getValue() {
   Array value = att.getValues();
   try {
     return NCdumpW.printArray(value, null, null);
   } catch (IOException e) {
     return e.getMessage();
   }
 }
Exemplo n.º 12
0
 public synchronized void send(String msg) {
   try {
     streamOut.writeUTF(msg);
   } catch (IOException ioe) {
     System.err.println("Sending error: " + ioe.getMessage());
     System.exit(0);
   }
 }
Exemplo n.º 13
0
  public void openLink(String link) {
    if (WWUtil.isEmpty(link)) return;

    try {
      try {
        // See if the link is a URL, and invoke the browser if it is
        URL url = new URL(link.replace(" ", "%20"));
        Desktop.getDesktop().browse(url.toURI());
        return;
      } catch (MalformedURLException ignored) { // just means that the link is not a URL
      }

      // It's not a URL, so see if it's a file and invoke the desktop to open it if it is.
      File file = new File(link);
      if (file.exists()) {
        Desktop.getDesktop().open(new File(link));
        return;
      }

      String message = "Cannot open resource. It's not a valid file or URL.";
      Util.getLogger().log(Level.SEVERE, message);
      this.showErrorDialog(null, "No Reconocido V\u00ednculo", message);
    } catch (UnsupportedOperationException e) {
      String message =
          "Unable to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "Error Opening Resource", message);
    } catch (IOException e) {
      String message =
          "I/O error while opening resource.\n"
              + link
              + (e.getMessage() != null ? ".\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "I/O Error", message);
    } catch (Exception e) {
      String message =
          "Error attempting to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message);
      this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE);
    }
  }
Exemplo n.º 14
0
  // read text from textArea through NcMLReader
  // then write it back out via resulting dataset
  private void checkNcml(Formatter f) {
    if (ncmlLocation == null) return;
    try {
      NetcdfDataset ncd = NetcdfDataset.openDataset(ncmlLocation);
      ncd.check(f);

    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage());
      ioe.printStackTrace();
    }
  }
Exemplo n.º 15
0
  private NetcdfDataset openDataset(String location, boolean addCoords, CancelTask task) {
    try {
      return NetcdfDataset.openDataset(location, addCoords, task);

      // if (setUseRecordStructure)
      //   ncd.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(null, "NetcdfDataset.open cant open " + ioe.getMessage());
      if (!(ioe instanceof java.io.FileNotFoundException)) ioe.printStackTrace();
      return null;
    }
  }
Exemplo n.º 16
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
Exemplo n.º 17
0
    @Override
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum((int) f.length());
        status.add(progress);
        status.revalidate();

        // try to start reading
        Reader in = new FileReader(f);
        char[] buff = new char[4096];
        int nch;
        while ((nch = in.read(buff, 0, buff.length)) != -1) {
          doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
          progress.setValue(progress.getValue() + nch);
        }
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not open file: " + msg,
                    "Error opening file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      doc.addUndoableEditListener(undoHandler);
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();

      resetUndoManager();

      if (elementTreePanel != null) {
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                elementTreePanel.setEditor(getEditor());
              }
            });
      }
    }
Exemplo n.º 18
0
 public File getCurrentFile(boolean shouldSave) {
   if (shouldSave && _editingFile == null && isDirty()) {
     try {
       saveAsFile(Settings.isMac());
     } catch (IOException e) {
       Debug.error(
           me + "getCurrentFile: Problem while trying to save %s\n%s",
           _editingFile.getAbsolutePath(),
           e.getMessage());
     }
   }
   return _editingFile;
 }
Exemplo n.º 19
0
 public String getData() {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   try {
     getDrawing().getOutputFormats().get(0).write(out, getDrawing());
     return out.toString("UTF8");
   } catch (IOException e) {
     SVGTextFigure tf = new SVGTextFigure();
     tf.setText(e.getMessage());
     tf.setBounds(new Point2D.Double(10, 10), new Point2D.Double(100, 100));
     getDrawing().add(tf);
     e.printStackTrace();
     return "";
   }
 }
Exemplo n.º 20
0
  @Override
  public void actionPerformed(ActionEvent ev) {
    if (ev.getSource() == btn) {
      File file;
      String string = "";
      try {
        if (radioRead.isSelected()) {
          file = new File(txt.getText());
          DataInputStream input = new DataInputStream(new FileInputStream(file));
          int inByte;
          while ((inByte = input.read()) != -1) {
            string += (char) inByte;
          }
          input.close();

        } else if (radioEncrypt.isSelected()) {
          string = fileContent.getOut();
          String strEncrypt = new String();
          for (int i = 0; i < string.length(); i++) {
            char ch = string.charAt(i);
            if (ch >= 'A' && ch <= 'Z') {
              ch += 13;
              if (ch > 'Z') {
                ch -= 26;
              }
            } else if (ch >= 'a' && ch <= 'z') {
              ch += 13;
              if (ch > 'z') {
                ch -= 26;
              }
            }
            strEncrypt += ch;
          }
          string = strEncrypt;
        }

        if (fileContent == null) {
          fileContent = new FileContent(string);
        } else {
          fileContent.setVisible(true);
          fileContent.setOut(string);
        }

      } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(this, "Can't find the file.");
      } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "IO Exception " + e.getMessage());
      }
    }
  }
 private static void doImport(
     @NotNull File newConfigDir,
     @NotNull File oldConfigDir,
     ConfigImportSettings settings,
     File installationHome) {
   try {
     copy(oldConfigDir, newConfigDir, settings, installationHome);
   } catch (IOException e) {
     JOptionPane.showMessageDialog(
         JOptionPane.getRootFrame(),
         ApplicationBundle.message("error.unable.to.import.settings", e.getMessage()),
         ApplicationBundle.message("title.settings.import.failed"),
         JOptionPane.WARNING_MESSAGE);
   }
 }
Exemplo n.º 22
0
 public File copyFileToBundle(String filename) {
   File f = new File(filename);
   String bundlePath = getSrcBundle();
   if (f.exists()) {
     try {
       File newFile = FileManager.smartCopy(filename, bundlePath);
       return newFile;
     } catch (IOException e) {
       Debug.error(
           me + "copyFileToBundle: Problem while trying to save %s\n%s", filename, e.getMessage());
       return f;
     }
   }
   return null;
 }
Exemplo n.º 23
0
  // read text from textArea through NcMLReader
  // then write it back out via resulting dataset
  void doTransform(String text) {
    try {
      StringReader reader = new StringReader(text);
      NetcdfDataset ncd = NcMLReader.readNcML(reader, null);
      StringWriter sw = new StringWriter(10000);
      ncd.writeNcML(sw, null);
      editor.setText(sw.toString());
      editor.setCaretPosition(0);
      JOptionPane.showMessageDialog(this, "File successfully transformed");

    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage());
      ioe.printStackTrace();
    }
  }
Exemplo n.º 24
0
  public static void lookingCode() {

    int procura = 0;
    boolean entrou = false;

    do {
      procura = Entrada.leiaInt("Digite o código da carta: ");
    } while (procura < 0 || procura > 32);

    try {
      FileReader arq = new FileReader(FileManenger.fileName);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha = lerArq.readLine();

      while (linha != null) {

        // procura na string '.'
        if (linha.toLowerCase().contains(".".toLowerCase())) {

          // separ em um array a linha que tem o nome do personagem ex: 1.CARLOS
          String columnArray[] = linha.split(Pattern.quote("."));

          // testa se o codigo é o que ele procura
          if (procura == Integer.parseInt(columnArray[0])) {

            // achou o codigo que ele procura
            entrou = true;
          }
        }

        // testa se a linha é igual a * se for ele já não é mais o personagem que procuramos
        if (linha.equals("*")) {
          entrou = false;
        }

        // mostra as inforamações do personagem
        if (entrou) {
          System.out.println(linha);
        }

        linha = lerArq.readLine();
      }

      arq.close();
    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }
  public static void main(String[] args) {

    MyCustomizableGUI custGUI = new MyCustomizableGUI();
    UserPreferences savedPrefs;

    try (FileInputStream fileIn = new FileInputStream("preferences.ser");
        ObjectInputStream objectIn = new ObjectInputStream(fileIn); ) {

      savedPrefs = (UserPreferences) objectIn.readObject();

      if (savedPrefs.getColor().contains("Red")) {
        custGUI.textField.setForeground(Color.red);
        custGUI.color.setSelectedItem("Red");
      } else if (savedPrefs.getColor().contains("Green")) {
        custGUI.textField.setForeground(Color.green);
        custGUI.color.setSelectedItem("Green");
      } else if (savedPrefs.getColor().contains("Blue")) {
        custGUI.textField.setForeground(Color.blue);
        custGUI.color.setSelectedItem("Blue");
      } else if (savedPrefs.getColor().contains("Cyan")) {
        custGUI.textField.setForeground(Color.cyan);
        custGUI.color.setSelectedItem("Cyan");
      } else if (savedPrefs.getColor().contains("Magenta")) {
        custGUI.textField.setForeground(Color.magenta);
        custGUI.color.setSelectedItem("Magenta");
      } else if (savedPrefs.getColor().contains("Yellow")) {
        custGUI.textField.setForeground(Color.yellow);
        custGUI.color.setSelectedItem("Yellow");
      } else if (savedPrefs.getColor().contains("Black")) {
        custGUI.textField.setForeground(Color.black);
        custGUI.color.setSelectedItem("Black");
      }

      custGUI.setFont(savedPrefs.getFont(), savedPrefs.getFontSize());
      custGUI.font.setSelectedItem(savedPrefs.getFont());
      custGUI.fontSize.setSelectedItem("" + savedPrefs.getFontSize());

    } catch (FileNotFoundException noFile) {
      // load default font and color
      custGUI.setFont("Arial", 25);
      custGUI.textField.setForeground(Color.black);

    } catch (ClassNotFoundException noPrefs) {
      noPrefs.printStackTrace();
    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    }
  }
Exemplo n.º 26
0
 private void openBin() {
   fileChooser.resetChoosableFileFilters();
   fileChooser.addChoosableFileFilter(binFilter);
   fileChooser.setFileFilter(binFilter);
   if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
     try {
       FileInputStream inbinf = new FileInputStream(fileChooser.getSelectedFile());
       int len = inbinf.available();
       if (len % 2 == 1) throw new IOException(String.format("Odd file size (0x%x)\n", len));
       len /= 2;
       if (len > 0x10000) throw new IOException(String.format("Too large file (0x%x)\n", len));
       binary = new char[len];
       for (int i = 0; i < len; i++) {
         int lo = inbinf.read();
         int hi = inbinf.read();
         if (lo == -1 || hi == -1) throw new IOException("Unable to read\n");
         binary[i] = (char) ((hi << 8) | lo);
       }
       asmMap = new AsmMap();
       Disassembler dasm = new Disassembler();
       dasm.init(binary);
       // TODO attach asmmap
       StringBuilder sb = new StringBuilder();
       while (dasm.getAddress() < binary.length) {
         int addr = dasm.getAddress();
         sb.append(String.format("%-26s ; [%04x] =", dasm.next(true), addr));
         int addr2 = dasm.getAddress();
         while (addr < addr2) {
           char i = binary[addr++];
           sb.append(
               String.format(" %04x '%s'", (int) i, (i >= 0x20 && i < 0x7f) ? (char) i : '.'));
         }
         sb.append("\n");
       }
       srcBreakpoints.clear();
       sourceRowHeader.breakpointsChanged();
       sourceTextarea.setText(sb.toString());
     } catch (IOException e1) {
       JOptionPane.showMessageDialog(
           frame, "Unable to open file: %s" + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
       e1.printStackTrace();
     }
   }
 }
Exemplo n.º 27
0
  private void SignInButtonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_SignInButtonActionPerformed

    /* username i password spojit u jedan string s delimiterom " ",
        prije toga nadodat kljucnu rijec "log"
        taj string se parsira na strani servera i server provjerava jel zadovoljava username i password
        (odgovor od servera slusa LoginThread koji salje odgovor Login-u preko handle metode)
    */
    String username = UsernameLogin.getText();
    String password = PasswordLogin.getText();
    String user_pass = "******" + " " + username + " " + password;

    try {
      streamOut.writeUTF(user_pass);
    } catch (IOException ioe) {
      System.err.println("Sending error: " + ioe.getMessage());
      System.exit(0);
    }
  } // GEN-LAST:event_SignInButtonActionPerformed
  private void writeAll() {
    List<MessageBean> beans = messageTable.getBeans();
    HashMap<Integer, Message> map = new HashMap<Integer, Message>(2 * beans.size());

    for (MessageBean mb : beans) {
      map.put(mb.m.hashCode(), mb.m);
    }

    if (fileChooser == null)
      fileChooser = new FileManager(null, null, null, (PreferencesExt) prefs.node("FileManager"));

    String defloc = (raf.getLocation() == null) ? "." : raf.getLocation();
    String dirName = fileChooser.chooseDirectory(defloc);
    if (dirName == null) return;

    try {
      int count = 0;
      for (Message m : map.values()) {
        String header = m.getHeader();
        if (header != null) {
          header = header.split(" ")[0];
        } else {
          header = Integer.toString(Math.abs(m.hashCode()));
        }

        File file = new File(dirName + "/" + header + ".bufr");
        FileOutputStream fos = new FileOutputStream(file);
        WritableByteChannel wbc = fos.getChannel();
        wbc.write(ByteBuffer.wrap(m.getHeader().getBytes()));
        byte[] raw = scan.getMessageBytes(m);
        wbc.write(ByteBuffer.wrap(raw));
        wbc.close();
        count++;
      }
      JOptionPane.showMessageDialog(
          BufrMessageViewer.this, count + " successfully written to " + dirName);

    } catch (IOException e1) {
      JOptionPane.showMessageDialog(BufrMessageViewer.this, e1.getMessage());
      e1.printStackTrace();
    }
  }
  private void jMenuItemLoadProjectActionPerformed(
      java.awt.event.ActionEvent evt) // GEN-FIRST:event_jMenuItemLoadProjectActionPerformed
      { // GEN-HEADEREND:event_jMenuItemLoadProjectActionPerformed
    JFileChooser jfc = new JFileChooser();
    if (lastPath != null) {
      jfc.setCurrentDirectory(lastPath);
    }
    int fileDialogReturnVal = jfc.showOpenDialog(this);

    if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
      try {
        File inputFile = jfc.getSelectedFile();
        FileInputStream fis = new FileInputStream(inputFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.theProject = (Project) ois.readObject();
        this.currentResults = (LSAResults) ois.readObject();

        lastPath = new File(jfc.getSelectedFile().getPath());
      } catch (IOException e) {
        if (this.theProject == null) {
          log.log(Log.ERROR, "Failed to load project");
        }
        if (this.currentResults == null) {
          log.log(Log.WARNING, "Failed to load results");
        }

        log.log(Log.WARNING, e.getMessage());
      } catch (ClassNotFoundException e) {
        log.log(Log.ERROR, "Class not found error, version mismatch");
      }
    }
    if (this.theProject != null) {
      jMenuItemViewDocuments.setEnabled(true);
      jMenuItemSaveProject.setEnabled(true);
      this.setTitle(theProject.getProjectName());
      log.log(Log.INFO, "Project Loaded");
    }
    if (this.currentResults != null) {
      log.log(Log.INFO, "Results loaded");
    }
  } // GEN-LAST:event_jMenuItemLoadProjectActionPerformed
Exemplo n.º 30
0
  public static void readFile() {

    try {

      FileReader arq = new FileReader(FileManenger.fileName);
      BufferedReader lerArq = new BufferedReader(arq);
      String linha =
          lerArq
              .readLine(); // lê a primeira linha a variável "linha" recebe o valor "null" quando o
                           // processo  de repetição atingir o final do arquivo texto
      while (linha != null) {
        System.out.println(linha);
        linha = lerArq.readLine(); // lê da segunda até a última linha
      }
      arq.close();

    } catch (IOException e) {
      System.err.printf("Erro na abertura do arquivo: %s.\n", e.getMessage());
    }
  }