/**
   * Save the downloaded files into the corresponding directories
   *
   * @deprecated
   */
  public synchronized void save() {
    synchronized (this) {
      synchronized (this.isComplete) {
        byte[] data = new byte[0];
        for (int i = 0; i < this.nbPieces; i++) {
          if (this.pieceList[i] == null) {

          } else {
            data = Utils.concat(data, this.pieceList[i].data());
          }
        }
        String saveAs = Constants.SAVEPATH;
        int offset = 0;
        if (this.nbOfFiles > 1) saveAs += this.torrent.saveAs + "/";
        for (int i = 0; i < this.nbOfFiles; i++) {
          try {
            new File(saveAs).mkdirs();
            FileOutputStream fos =
                new FileOutputStream(saveAs + ((String) (this.torrent.name.get(i))));
            fos.write(
                Utils.subArray(data, offset, ((Integer) (this.torrent.length.get(i))).intValue()));
            fos.flush();
            fos.close();
            offset += ((Integer) (this.torrent.length.get(i))).intValue();
          } catch (IOException ioe) {
            ioe.printStackTrace();
            System.err.println(
                "Error when saving the file " + ((String) (this.torrent.name.get(i))));
          }
        }
      }
    }
  }
  // Merge the availableChunks to build the original file
  void MergeChunks(File[] chunks) throws IOException {

    // Safety check
    if (chunks == null) {
      System.err.println("ERROR: No chunks to merge!");
      return;
    }

    FileOutputStream fos = new FileOutputStream("complete/" + filename);

    try {
      FileInputStream fis;
      byte[] fileBytes;
      int bytesRead;
      for (File f : chunks) {
        fis = new FileInputStream(f);
        fileBytes = new byte[(int) f.length()];
        bytesRead = fis.read(fileBytes, 0, (int) f.length());
        assert (bytesRead == fileBytes.length);
        assert (bytesRead == (int) f.length());
        fos.write(fileBytes);
        fos.flush();
        fileBytes = null;
        fis.close();
        fis = null;
      }
    } catch (Exception exception) {
      exception.printStackTrace();
    } finally {
      fos.close();
      fos = null;
    }
  }
Example #3
0
  /**
   * @param in the InputStream, i.e. the source, closes the passed input stream
   * @param fn where to output the file (numbers are ok)
   */
  protected final void fileForShow(InputStream in, String fn) {
    File f = (((fn == null) || fn.equals("")) ? DEF_FILE : getFile(fn));
    boolean fout = "true".equals(System.getProperty("file.echo"));

    try {
      FileOutputStream out = new FileOutputStream(f);
      int b = 0;

      while ((b = in.read()) != -1) {
        if (fout) {
          Console.out.write(b);
        }

        out.write(b);
      }

      out.flush();
      out.close();
      Console.out.flush();
      in.close();
      s_showFile = f;
    } catch (Exception exp) {
      System.err.println("FAILED TO WRITE TO OUTPUT FILE " + f.getAbsolutePath());
      exp.printStackTrace();
    }
  }
Example #4
0
  public String unzip(String destinationName, String zipFileName) {
    String rootFolder = null;

    try {
      byte[] buf = new byte[1024];
      ZipInputStream zipinputstream;
      ZipEntry zipentry;
      zipinputstream = new ZipInputStream(new FileInputStream(zipFileName));
      boolean isFirstRun = true;

      zipentry = zipinputstream.getNextEntry();
      while (zipentry != null) {
        // for each entry to be extracted
        String entryName = destinationName + zipentry.getName();
        entryName = entryName.replace('/', File.separatorChar);
        entryName = entryName.replace('\\', File.separatorChar);
        System.out.println("entryname " + entryName);
        int n;
        File newFile = new File(entryName);
        if (isFirstRun && !zipentry.isDirectory()) {
          fail("zip file must contain folder at root");
        } else {
          isFirstRun = false;
          rootFolder = zipentry.getName();
        }
        if (zipentry.isDirectory()) {
          if (!newFile.mkdirs()) {
            break;
          }
          zipentry = zipinputstream.getNextEntry();
          continue;
        }

        FileOutputStream fileoutputstream = new FileOutputStream(entryName);

        while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
          fileoutputstream.write(buf, 0, n);
        }

        fileoutputstream.flush();
        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();
      } // while

      zipinputstream.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
    return rootFolder;
  }
Example #5
0
  /**
   * Create an archive in the specified File containing entries for the data contained in the
   * streams supplied entries arg. specifying the entry name and the value is a InputStream
   * containing the entry data.
   *
   * @param file The archive file.
   * @throws java.io.IOException Write failure.
   */
  public void toFile(File file) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream(file);

    try {
      toOutputStream(new ZipOutputStream(fileOutputStream));
    } finally {
      try {
        fileOutputStream.flush();
      } finally {
        fileOutputStream.close();
      }
    }
  }
Example #6
0
 public void save() {
   try {
     if (mModel != null) {
       JXMLBaseObject cobjXmlObj = mModel.toXml();
       String dataStr = cobjXmlObj.GetRootXMLString();
       FileOutputStream FOS = new FileOutputStream(FILE_PATH);
       FOS.write(dataStr.getBytes());
       FOS.flush();
       FOS.close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Example #7
0
  public File download(String songId) {
    try {
      String maxRate = getMaxRate(songId);
      JSONObject songInfo = getSongInfo(songId);
      // 以歌手名字+歌曲名称组成文件名,格式:歌手 - 歌曲名称
      String filename = songInfo.getString("artistName") + " - " + songInfo.getString("songName");

      String link =
          "http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds="
              + songId
              + "&rate="
              + maxRate;

      URL urlObject = new URL(link);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setRequestProperty("Cookie", cookieValue);
      String disposition = httpUrlConnection.getHeaderField("Content-Disposition");
      disposition = disposition.replaceAll("\"", "");
      // 此转码经测试发现有些是UTF-8编码,有些是GBK编码,所以文件名采用另外方式获得
      // disposition = new String(disposition.getBytes("iso-8859-1"),"UTF-8");

      // 根据disposition中信息确定歌曲格式
      String suffix = disposition.substring(disposition.lastIndexOf("."));
      // System.out.println(disposition);

      InputStream inputStream = httpUrlConnection.getInputStream();

      File file = new File(downloadDirectory + "/" + filename + suffix);
      FileOutputStream fos = new FileOutputStream(file);

      byte[] buf = new byte[4096];
      int read = 0;
      while ((read = inputStream.read(buf)) > 0) {
        fos.write(buf, 0, read);
      }
      fos.flush();
      fos.close();
      inputStream.close();
      // System.out.println("完成<"+file.getName()+">歌曲下载!");
      return file;

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  private void save(FileOutputStream os) throws IOException {
    // write the version number
    os.write(KEYRING_FILE_VERSION);

    CipherOutputStream cos = new CipherOutputStream(os, password);
    ObjectOutputStream oos = new ObjectOutputStream(cos);
    // write the data
    try {
      oos.writeObject(authorizationInfo);
      oos.writeObject(protectionSpace);
      os.flush();
      os.getFD().sync();
    } finally {
      oos.close();
    }
  }
Example #9
0
 public void close() throws IOException {
   FileOutputStream fout = new FileOutputStream(fileName);
   workbook.write(fout);
   fout.flush();
   fout.close();
 }
Example #10
0
  /** Create data. */
  private void createData() {
    try {
      String[] categories = new String[] {"Hardware", "Software"};
      String[][] subCategories =
          new String[][] {
            {"PC", "Monitor", "Printer"},
            {"O.S.", "IDEs", "Office Appl.", "Database", "Games", "Other SW"}
          };
      String[] agents = new String[] {"Agent 1", "Agent 2", "Agent 3"};
      String[] countries = new String[] {"Italy", "France", "Germany", "Other"};
      String[][] zones =
          new String[][] {
            {"North Italy", "Center Italy", "South Italy"},
            {"Paris", "Outside Paris"},
            {"East", "West"},
            {"Iberica Peninsula", "U.K. & Ireland", "Be.Ne.Lux.", "East Europe"}
          };
      HashMap items = new HashMap();
      items.put("PC", new String[] {"Dell", "HP"});
      items.put("Monitor", new String[] {"LG", "Sony", "Philips"});
      items.put("Printer", new String[] {"HP", "Epson"});
      items.put("O.S.", new String[] {"Windows", "Linux", "Mac"});
      items.put("IDEs", new String[] {"JBuilder", "IBM RAD", "MS Visual Studio .NET"});
      items.put("Office Appl.", new String[] {"MS Office 2007", "Open Office"});
      items.put("Database", new String[] {"Oracle", "MS SQLServer", "Sybase", "IBM DB2"});
      items.put("Games", new String[] {"Need4Speed", "Fifa"});
      items.put("Other SW", new String[] {"Norton AV", "Photoshop"});

      FileOutputStream out = new FileOutputStream("orders.txt");
      String line = null;
      int i = 0;
      Calendar cal = Calendar.getInstance();
      cal.set(cal.YEAR, 2007);
      cal.set(cal.MONTH, 0);
      cal.set(cal.DAY_OF_MONTH, 1);
      cal.set(cal.HOUR_OF_DAY, 0);
      cal.set(cal.MINUTE, 0);
      cal.set(cal.SECOND, 0);
      cal.set(cal.MILLISECOND, 0);
      long t = cal.getTimeInMillis();
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      String date = null;
      int maxRows = 2000000;
      String[] ii = null;
      String[] sub = null;
      String[] z = null;
      do {
        date = sdf.format(new java.util.Date(t));
        for (int k1 = 0; k1 < categories.length; k1++) {
          sub = subCategories[k1];
          for (int k2 = 0; k2 < sub.length; k2++) {
            if (i >= maxRows) break;
            for (int k3 = 0; k3 < countries.length; k3++) {
              z = zones[k3];
              for (int k4 = 0; k4 < z.length; k4++)
                for (int k5 = 0; k5 < agents.length; k5++) {
                  if (i >= maxRows) break;
                  ii = (String[]) items.get(sub[k2]);
                  for (int k6 = 0; k6 < ii.length; k6++) {
                    if (i >= maxRows) break;

                    line =
                        date
                            + ";"
                            + categories[k1]
                            + ";"
                            + sub[k2]
                            + ";"
                            + countries[k3]
                            + ";"
                            + z[k4]
                            + ";"
                            + agents[k5]
                            + ";"
                            + ii[k6]
                            + ";"
                            + new BigDecimal(Math.random() * 10)
                                .setScale(0, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + new BigDecimal(Math.random() * 1000)
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + "\n";
                    out.write(line.getBytes());
                    out.flush();
                    i++;
                  }
                }
            }
          }
        }
        t += 86400000;
      } while (i < maxRows);
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Example #11
0
  /**
   * Método public static void guardarArchivoXML(ListaUsuarios listaDeUsuarios): Este método permite
   * guardar la lista de usuarios en un archivo XML. El procesamiento se hace con jdom
   */
  public static void guardarArchivoXML(ListaUsuario listaDeUsuarios) {
    Usuario nodoAuxiliar;

    /* Se crea una raiz de la estructura */
    Element root = new Element("usuarios");

    /* Es posible agregar atributos a la estructura inicial */
    root.setAttribute("tipo", "lista de usuarios");

    Iterator iterador = listaDeUsuarios.getIterator();

    while (iterador.hasNext()) {
      /* Se crea la etiqueta "usuario" */
      Element usuarios = new Element("usuario");

      nodoAuxiliar = (Usuario) iterador.next();

      /* Se crean las etiquetas nombre, apellido y cargo */
      Element nick = new Element("nick");
      Element clave = new Element("clave");
      Element nombre = new Element("nombre");
      Element apellido = new Element("apellido");
      Element fechanac = new Element("fechanac");
      Element avatar = new Element("avatar");

      /* Se inicializa cada etiqueta con sus valores de la lista */
      nick.setText(nodoAuxiliar.getNickname());
      clave.setText(nodoAuxiliar.getClave());
      nombre.setText(nodoAuxiliar.getNombre());
      apellido.setText(nodoAuxiliar.getApellido());
      fechanac.setText(nodoAuxiliar.getFechanaci());
      avatar.setText(nodoAuxiliar.getAvatar());

      /* Se añaden las etiquetas a la etiqueta principal (usuario)    */
      /* estableciendo que un usuario tiene nombre, apellido y cargo  */
      usuarios.addContent(nick);
      usuarios.addContent(clave);
      usuarios.addContent(nombre);
      usuarios.addContent(apellido);
      usuarios.addContent(fechanac);
      usuarios.addContent(avatar);

      /* Se añade el nuevo usuario a la estructura XML */
      root.addContent(usuarios);
    }

    /* Se crea un documento nuevo */
    Document doc = new Document(root);

    try {
      /* Se genera un flujo de salida de datos XML */
      XMLOutputter out = new XMLOutputter();

      /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */
      FileOutputStream file = new FileOutputStream(nombreArchivo);

      /* Se manda el documento generado hacia el archivo XML */
      out.output(doc, file);

      /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */
      file.flush();
      file.close();

      /* En este caso se manda a imprimir el archivo por la consola   */
      /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML          */
      out.output(doc, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #12
0
  public static void guardarArchivoXML(ListaPartida listaDePartidas, boolean valor) {
    Ficha nodoAuxiliarPote;
    Ficha nodoAuxiliarUsuario;
    Ficha nodoAuxiliarServidor;
    Partida partidaActual;
    Ficha fichaActual;

    /* Se crea una raiz de la estructura */
    Element root = new Element("fichas");

    /* Es posible agregar atributos a la estructura inicial */
    root.setAttribute("tipo", "lista de fichas");

    Iterator iteradorPartida = listaDePartidas.getIterator();
    Iterator iteradorFichaUsuario;
    Iterator iteradorFichaPote;
    Iterator iteradorFichaServidor;

    Element ID;
    Element fichaPote;
    Element fichaUsuario;
    Element fichaServidor;
    Element fichaX;
    Element fichaY;

    while (iteradorPartida.hasNext()) {
      ID = new Element("ID");
      fichaPote = new Element("fichapote");
      fichaUsuario = new Element("fichausuario");
      fichaServidor = new Element("fichaservidor");

      partidaActual = (Partida) iteradorPartida.next();

      ID.setAttribute("id", Integer.toString(partidaActual.getID()));

      iteradorFichaPote = partidaActual.getFichapote().getIterator();

      while (iteradorFichaPote.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaPote.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaPote.addContent(fichaX);
        fichaPote.addContent(fichaY);
      }

      ID.addContent(fichaPote);

      iteradorFichaUsuario = partidaActual.getFichausuario().getIterator();

      while (iteradorFichaUsuario.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaUsuario.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaUsuario.addContent(fichaX);
        fichaUsuario.addContent(fichaY);
      }

      ID.addContent(fichaUsuario);

      iteradorFichaServidor = partidaActual.getFichaservidor().getIterator();

      while (iteradorFichaServidor.hasNext()) {
        fichaX = new Element("X");
        fichaY = new Element("Y");
        fichaActual = (Ficha) iteradorFichaServidor.next();
        fichaX.setText(Integer.toString(fichaActual.getX()));
        fichaY.setText(Integer.toString(fichaActual.getY()));
        fichaServidor.addContent(fichaX);
        fichaServidor.addContent(fichaY);
      }

      ID.addContent(fichaServidor);

      root.addContent(ID);
    }

    /* Se crea un documento nuevo */
    Document doc = new Document(root);

    try {
      /* Se genera un flujo de salida de datos XML */
      XMLOutputter out = new XMLOutputter();

      /* Se asocia el flujo de salida con el archivo donde se guardaran los datos */
      FileOutputStream file = new FileOutputStream(nombreArchivoFicha);

      /* Se manda el documento generado hacia el archivo XML */
      out.output(doc, file);

      /* Se limpia el buffer ocupado por el objeto file y se manda a cerrar el archivo */
      file.flush();
      file.close();

      /* En este caso se manda a imprimir el archivo por la consola   */
      /* ESTE PROCESO NO ES OBLIGATORIO PARA PROCESAR EL XML          */
      out.output(doc, System.out);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }