public static void main(String[] args) throws IOException {

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    String f1, f2, f3;

    f1 = reader.readLine();
    f2 = reader.readLine();
    f3 = reader.readLine();

    FileOutputStream file1 = new FileOutputStream(f1);
    FileInputStream file2 = new FileInputStream(f2);
    FileInputStream file3 = new FileInputStream(f3);

    byte buf[] = new byte[1000];
    while (file2.available() > 0) {
      int count = file2.read(buf);
      file1.write(buf, 0, count);
    }

    while (file3.available() > 0) {
      int count = file3.read(buf);
      file1.write(buf, 0, count);
    }

    file1.close();
    file2.close();
    file3.close();
  }
Example #2
0
  /** Checks the Bytes for the UTF-8 BOM if found, returns true, else false */
  private boolean isUTF8File(File file) {

    FileInputStream stream = null;

    // UTF-8 BOM is 0xEE 0xBB OxBf
    // or 239 187 191

    try {
      stream = new FileInputStream(file);

      if (stream.read() == 239) {
        if (stream.read() == 187) {
          if (stream.read() == 191) {
            return true;
          }
        }
      }
    } catch (FileNotFoundException e) {
      LOGGER.error("Error in file when testing CSV");
    } catch (IOException io) {
      LOGGER.error("IO error when testing file");
    } finally {
      IOUtils.closeQuietly(stream);
    }
    return false;
  }
Example #3
0
 public void aKeAt(String sumber, String sasaran) throws IOException {
   FileInputStream masukan = null;
   FileOutputStream keluaran = null;
   // Deklarasi variabel
   try {
     // Object stream untuk masukkan
     masukan = new FileInputStream(sumber);
     keluaran = new FileOutputStream(sasaran);
     // Coba baca  dari stream
     int karakter = masukan.read();
     // Selama masih ada data yang masih bisa dibaca
     while (karakter != -1) {
       // Lakukan sesuatu dengan data yang dibaca => Tampikan
       if (karakter == 'a' || karakter == 'A') {
         keluaran.write('@');
       } else {
         keluaran.write(karakter);
       }
       karakter = masukan.read();
     }
     keluaran.flush();
   } catch (IOException kesalahan) {
     System.out.print("Terjadi kesalahan : %s, kesalahan");
   } finally {
     // Tutup stream masukan
     if (masukan != null) masukan.close();
     if (keluaran != null) keluaran.close();
   }
 }
  public void kopi(String sumber, String sasaran) throws IOException {
    FileInputStream masukan = null;
    FileOutputStream keluaran = null;

    // Deklarasi variabel
    try {
      // Object stream untuk masukkan
      masukan = new FileInputStream(sumber);
      keluaran =
          new FileOutputStream(
              sasaran); // ambil objek abestu bukak nama berkasnya kalaok ga ada dia throw
      // excepytion

      // Coba baca  dari stream
      int karakter = masukan.read();
      // Selama masih ada data yang masih bisa dibaca
      while (karakter != -1) { // kalau minus 1 dia selesai
        // Lakukan sesuatu dengan data yang dibaca => Tampikan
        keluaran.write(karakter);
        // Coba baca lagi dari stream
        karakter = masukan.read();
      }
      keluaran.flush();
    } finally {
      // Tutup stream masukan
      if (masukan != null) masukan.close();
      if (keluaran != null) keluaran.close();
    }
  }
  String getToken(byte bary[], int idx[], byte cr[]) throws IOException {
    int b;
    int i = 0;

    // Discard the leading spaces.
    do {
      b = input.read();
      if (b < 0) break;
      bary[idx[0]++] = (byte) b;
    } while (b == ' ' || b == '\t' || b == '*' || b == '/' || b == 10 || b == 13);

    while (true) {
      if (b == ' ' || b == '\t' || b == 10 || b == 13) {
        if (cr != null && (b == 10 || b == 13)) cr[0] = (byte) b;
        break;
      } else token[i++] = (byte) b;

      b = input.read();
      if (b < 0) break;
      bary[idx[0]++] = (byte) b;
    }

    if (i == 0) return null;

    return new String(token, 0, i);
  }
 public void sendStaticResource() throws IOException {
   byte[] bytes = new byte[BUFFER_SIZE];
   FileInputStream fis = null;
   try {
     File file = new File(HttpServer.WEB_ROOT, request.getUri());
     if (file.exists()) {
       fis = new FileInputStream(file);
       int ch = fis.read(bytes, 0, BUFFER_SIZE);
       while (ch != -1) {
         output.write(bytes, 0, ch);
         ch = fis.read(bytes, 0, BUFFER_SIZE);
       }
     } else {
       // file not found
       String errorMessage =
           "HTTP/1.1 404 File Not Found\r\n"
               + "Content-Type: text/html\r\n"
               + "Content-Length: 23\r\n"
               + "\r\n"
               + "<h1>File Not Found</h1>";
       output.write(errorMessage.getBytes());
     }
   } catch (Exception e) {
     // thrown if cannot instantiate a File object
     System.out.println(e.toString());
   } finally {
     if (fis != null) fis.close();
   }
 }
Example #7
0
  public static void parsePKCS7(String pkcs7Path, String signPath) {
    try {
      File f = new File("test_cert.der");
      FileInputStream is = new FileInputStream(f);
      byte[] cert = new byte[(int) f.length()];
      is.read(cert);
      is.close();

      f = new File("test_signed.bin");
      is = new FileInputStream(f);
      byte[] signedData = new byte[(int) f.length()];
      is.read(signedData);
      is.close();

      f = new File("test.SF");
      is = new FileInputStream(f);
      byte[] signData = new byte[(int) f.length()];
      is.read(signData);
      is.close();

      boolean result = verifySignedData(signData, signedData, cert);
      System.out.println("verified:" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #8
0
  /**
   * Reads and returns the file corresponding to the given path.
   *
   * @param string
   * @return
   */
  private String readfile(String string) {
    FileInputStream fis = null;
    String algorithmAsString = "";
    try {
      fis = new FileInputStream(string);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    }

    int b = 1;
    try {
      b = fis.read();
    } catch (IOException e) {
      e.printStackTrace();
    }

    while (b > 0) {
      algorithmAsString += (char) b;
      try {
        b = fis.read();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return algorithmAsString;
  }
Example #9
0
  public static KeyPair LoadKeyPair(String path, String algorithm)
      throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(path + "/public.key");
    FileInputStream fis = new FileInputStream(path + "/public.key");
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(path + "/private.key");
    fis = new FileInputStream(path + "/private.key");
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
  }
Example #10
0
  public Palette(String filename, boolean remapTransparent) throws IOException {
    colors = new long[256];

    FileInputStream reader;

    try {
      reader = new FileInputStream(filename);

      for (int i = 0; i < 256; i++) {
        byte r = (byte) (reader.read() << 2);
        byte g = (byte) (reader.read() << 2);
        byte b = (byte) (reader.read() << 2);
        colors[i] = (long) ((255 << 24) | (r << 16) | (g << 8) | b);
      }

      colors[0] = 0;
      if (remapTransparent) {
        colors[1] = 178 << 24; // Hack for d2k; may have side effects
        colors[3] = 178 << 24;
        colors[4] = 140 << 24;
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #11
0
 public static String readKeyFromFile(String fileName) {
   String result = "";
   File tempFile = new File(fileName);
   FileInputStream io = null;
   try {
     io = new FileInputStream(tempFile);
     byte[] buf = new byte[512];
     int size = io.read(buf);
     while (size > 0) {
       result += new String(buf, 0, size);
       size = io.read(buf);
     }
   } catch (FileNotFoundException e1) {
     e1.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       if (io != null) io.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   return decodeString(result);
 }
Example #12
0
  public static StringBuilder readFileContent(String filePath, String unicode)
      throws JDependException {

    assert filePath != null && filePath.length() != 0;
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(filePath);
      byte[] buf = new byte[1024];
      StringBuilder sb = new StringBuilder();
      int length = fis.read(buf);
      while (length != -1) {
        sb.append(new String(buf, 0, length, unicode));
        buf = new byte[1024];
        length = fis.read(buf);
      }
      return sb;
    } catch (FileNotFoundException e) {
      LogUtil.getInstance(FileUtil.class).systemError("文件[" + filePath + "]读取失败。");
      throw new JDependException("文件[" + filePath + "]读取失败。", e);
    } catch (IOException e) {
      LogUtil.getInstance(FileUtil.class).systemError("文件[" + filePath + "]读取失败。");
      throw new JDependException("文件[" + filePath + "]读取失败。", e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  // method from TA
  private boolean copyfile(String sourceFilename, String destinationFilename) {
    FileInputStream bis = null;
    FileOutputStream bos = null;

    try {
      // bis -> buf -> bos
      bis = new FileInputStream(sourceFilename);
      bos = new FileOutputStream(destinationFilename, false);
      byte[] buf = new byte[4 * 1024];
      bis.read(buf);
      do {
        bos.write(buf);
      } while (bis.read(buf) != -1);
    } catch (Exception e) {
      return false;
    } finally {
      try {
        if (bis != null) bis.close();
        if (bos != null) bos.close();
      } catch (IOException e) {
      }
    }

    return true;
  }
Example #14
0
  /**
   * Loads and parses configuration file.
   *
   * @param file configuration file.
   * @throws IOException if input/output error occurs.
   */
  public ConfigFile(File file) throws IOException {
    this.file = file;
    BufferedReader in;

    FileInputStream fis = new FileInputStream(file);
    int magick = fis.read() | (fis.read() << 8);
    fis.close();

    in =
        magick == GZIPInputStream.GZIP_MAGIC
            ? new BufferedReader(
                new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), "UTF-8"))
            : new BufferedReader(new FileReader(file));

    String line;
    while ((line = in.readLine()) != null) {
      line = line.trim();
      if (line.length() == 0) continue;
      if (line.charAt(0) == '#' || line.charAt(0) == ';') continue;

      int pos = line.indexOf(':');
      if (pos < 1) continue;

      String key = line.substring(0, pos).trim().toLowerCase();
      String value = line.substring(pos + 1).trim();
      if (key.length() == 0 || value.length() == 0) continue;
      String old = get(key);
      put(key, old == null ? value : (old + "\n" + value));
    }

    in.close();
  }
 public void sendStaticResource() {
   FileInputStream fis = null;
   try {
     File file = new File(HttpServer.WEB_ROOT, request.getUri());
     byte[] buffer = new byte[BUFFER_SIZE];
     if (file.exists()) {
       fis = new FileInputStream(file);
       int len = fis.read(buffer, 0, BUFFER_SIZE);
       while (len != -1) {
         output.write(buffer, 0, len);
         len = fis.read(buffer, 0, BUFFER_SIZE);
       }
     } else {
       String errorMessage =
           "HTTP/1.1 404 File Not Found\r\n"
               + "Content-Type:text/html\r\n"
               + "Content-Length:23\r\n"
               + "\r\n"
               + "<h1>File Not Found</h1>";
       output.write(errorMessage.getBytes());
     }
   } catch (IOException e) {
     System.out.println(e.toString());
   } finally {
     if (fis != null) {
       try {
         fis.close();
       } catch (IOException e) {
       }
     }
   }
 }
Example #16
0
  public void openFile(String filename) {
    try {
      FileInputStream input = new FileInputStream(filename);
      char x;

      for (int i = 0; i < 9; i++) {
        for (int j = 0; j < 9; j++) {
          x = (char) input.read();

          if (x == 'P') {
            puzzleBox[i][j].setText(String.valueOf((char) input.read()));
            puzzleBox[i][j].setEnabled(false);
          } else {
            x = (char) input.read();

            if (x == 'X') {
              puzzleBox[i][j].setText("");
              puzzleBox[i][j].setEnabled(true);
            } else {
              puzzleBox[i][j].setText(String.valueOf(x));
              puzzleBox[i][j].setEnabled(true);
            }
          }
        }

        x = (char) input.read();
        x = (char) input.read();
      }

      input.close();
    } catch (IOException ioException) {
      JOptionPane.showMessageDialog(this, "Error Opening File", "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
Example #17
0
  /** Check if the file at 'path' starts with a cart header */
  private boolean isCartFormat(String path) throws Exception {
    FileInputStream fs = null;
    try {
      // check if the first 4 bytes spell CART
      fs = new FileInputStream(path);
      if (fs.read() != 67) return false; // C
      if (fs.read() != 65) return false; // A
      if (fs.read() != 82) return false; // R
      if (fs.read() != 84) return false; // T

      // extract the ehcksum from the header
      byte[] checksumBytes = new byte[4];
      fs.read(checksumBytes);
      fs.read(checksumBytes);
      fs.close();
      fs = null;
      // if the checksums match we have a CART
      if (decodeInt(checksumBytes, 0) == atariChecksum(path, 16)) {
        return true;
      }

      return false;
    } catch (Throwable e) {
      throw new Exception("Exception in isCartFormat", e);
    } finally {
      if (fs != null) {
        try {
          fs.close();
        } catch (Throwable e) {
          throw new Exception("Exception closing stream", e);
        }
      }
    }
  }
Example #18
0
 public static void odczytPlikuTekstowegoD() throws IOException {
   // dekrypt
   BufferedWriter writer = new BufferedWriter(new FileWriter("odszyfrowanie.txt"));
   FileInputStream fileInput = new FileInputStream("zaszyfrowany.txt");
   FileInputStream filen = new FileInputStream("n.txt");
   FileInputStream filed = new FileInputStream("d.txt");
   String nfile = "";
   String dfile = "";
   int r;
   while ((r = filen.read()) != -1) {
     nfile += (char) r;
   }
   while ((r = filed.read()) != -1) {
     dfile += (char) r;
   }
   filen.close();
   filed.close();
   // System.out.println(dfile);
   // System.out.println(nfile);
   BigInteger n = new BigInteger(nfile);
   BigInteger d = new BigInteger(dfile);
   String content = new String(Files.readAllBytes(Paths.get("zaszyfrowany.txt")));
   String[] odczytane = content.split(" ");
   for (String o : odczytane) {
     BigInteger wynik = new BigInteger(o).modPow(d, n);
     writer.write(new String(wynik.toByteArray()));
   }
   writer.close();
   fileInput.close();
 }
Example #19
0
  public void run() {

    byte[] tmp = new byte[10000];
    int read;
    try {
      FileInputStream fis = new FileInputStream(fileToSend.getFile());

      read = fis.read(tmp);
      while (read != -1) {
        baos.write(tmp, 0, read);
        read = fis.read(tmp);
        System.out.println(read);
      }
      fis.close();
      baos.writeTo(sWriter);
      sWriter.flush();
      baos.flush();
      baos.close();
      System.out.println("fileSent");
    } catch (IOException e) {
      e.printStackTrace();
    } finally {

      this.closeSocket();
    }
  }
Example #20
0
  public static FileDesc loadFile(Path root, Path file, int blocSize)
      throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    MessageDigest fileMd = MessageDigest.getInstance("SHA-512");

    FileDesc desc = new FileDesc(file.toString(), null, null);
    List<Bloc> list = new ArrayList<Bloc>();
    try (FileInputStream fis = new FileInputStream(root.resolve(file).toString())) {
      byte[] buf = new byte[blocSize];
      byte[] h;
      int s;
      while ((s = fis.read(buf)) != -1) {
        int c;
        while (s < buf.length && (c = fis.read()) != -1) buf[s++] = (byte) c;
        fileMd.update(buf, 0, s);

        // padding
        byte p = 0;
        while (s < buf.length) buf[s++] = ++p;
        h = md.digest(buf);
        Bloc bloc = new Bloc(RollingChecksum.compute(buf), new Hash(h));
        list.add(bloc);
      }
      h = fileMd.digest();
      desc.fileHash = new Hash(h);
      desc.blocs = list.toArray(new Bloc[0]);
    }
    return desc;
  }
Example #21
0
 /**
  * Zip up a directory path
  *
  * @param directory
  * @param zos
  * @param path
  * @throws IOException
  */
 private static void zipDir(String directory, ZipOutputStream zos, String path)
     throws IOException {
   File zipDir = new File(directory);
   // get a listing of the directory content
   String[] dirList = zipDir.list();
   byte[] readBuffer = new byte[2156];
   int bytesIn = 0;
   // loop through dirList, and zip the files
   for (int i = 0; i < dirList.length; ++i) {
     File f = new File(zipDir, dirList[i]);
     if (f.isDirectory()) {
       zipDir(f.getPath(), zos, path.concat(f.getName()).concat(FILE_SEPARATOR));
       continue;
     }
     FileInputStream fis = new FileInputStream(f);
     try {
       zos.putNextEntry(new ZipEntry(path.concat(f.getName())));
       bytesIn = fis.read(readBuffer);
       while (bytesIn != -1) {
         zos.write(readBuffer, 0, bytesIn);
         bytesIn = fis.read(readBuffer);
       }
     } finally {
       closeQuietly(fis);
     }
   }
 }
Example #22
0
  public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String file1 = reader.readLine();
    String file2 = reader.readLine();

    FileInputStream inputStream1 = new FileInputStream(file1);
    FileInputStream inputStream2 = new FileInputStream(file2);
    ArrayList<Integer> list = new ArrayList<>();
    while (inputStream2.available() > 0) {
      list.add(inputStream2.read());
    }
    while (inputStream1.available() > 0) {
      list.add(inputStream1.read());
    }
    FileOutputStream outputStream = new FileOutputStream(file1);

    for (Integer pair : list) {
      System.out.println(pair);

      outputStream.write(pair);
    }
    reader.close();
    inputStream1.close();
    inputStream2.close();
    outputStream.close();
  }
Example #23
0
 /**
  * Get the image binary data, with hexical output. For RTF transformation
  *
  * @param dirName - The directory name that will be added to the path of the image file.
  * @param fileName - The file name of the image file.
  * @return java.lang.String - The Hexical binary of image data converted to String.
  */
 public static String getBinData(final String dirName, final String fileName) {
   final DITAOTJavaLogger logger = new DITAOTJavaLogger();
   final File imgInput = new File(dirName, toFile(fileName).getPath());
   FileInputStream binInput = null;
   try {
     String binStr = null;
     final StringBuilder ret = new StringBuilder(16 * 1024);
     binInput = new FileInputStream(imgInput);
     int bin = binInput.read();
     while (bin != -1) {
       binStr = Integer.toHexString(bin);
       if (binStr.length() < 2) {
         ret.append("0");
       }
       ret.append(binStr);
       bin = binInput.read();
     }
     return ret.toString();
   } catch (final Exception e) {
     logger.error(MessageUtils.getInstance().getMessage("DOTJ023E").toString());
     logger.error(e.getMessage(), e);
     return null;
   } finally {
     if (binInput != null) {
       try {
         binInput.close();
       } catch (final IOException ioe) {
         logger.error(ioe.getMessage(), ioe);
       }
     }
   }
 }
Example #24
0
  public static void readFile() {
    FileInputStream fis = null;
    try {
      // 创建流对象
      fis = new FileInputStream("src/org/ucas/test/demo.txt");
      // 读取数据到数组中
      byte[] data = new byte[1204]; // 数据存储的数组
      int i = 0; // 当前小标
      // 读取流中的第一个字节数据
      int n = fis.read();
      //            fis.read(data);
      //            fis.read(data,1,2);
      // 依次读取后续的数据
      while (n != -1) {
        data[i] = (byte) n;
        i++;
        n = fis.read(); // 读一个字节
      }
      // 解析数据
      String s = new String(data, 0, i);
      System.out.println(s);

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        fis.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #25
0
  private long readNumber(int precision) throws IOException {
    long number;

    if (precision < 7) {
      byte[] buf = new byte[2];
      str.read(buf);
      number = buf[0] & 0xff;
      number |= (buf[1] & 0xff) << 0x08;
    } else if (precision < 12) {
      byte[] buf = new byte[4];
      str.read(buf);
      number = buf[0] & 0xff;
      number |= (buf[1] & 0xff) << 0x08;
      number |= (buf[2] & 0xff) << 0x10;
      number |= (buf[3] & 0xff) << 0x18;
    } else {
      byte[] buf = new byte[8];
      str.read(buf);
      number = buf[0] & 0xff;
      number |= (buf[1] & 0xff) << 0x08;
      number |= (buf[2] & 0xff) << 0x10;
      number |= (buf[3] & 0xff) << 0x18;
      number |= (buf[4] & 0xff) << 0x20;
      number |= (buf[5] & 0xff) << 0x28;
      number |= (buf[6] & 0xff) << 0x30;
      number |= (buf[7] & 0xff) << 0x38;
    }

    return number;
  }
  // 不能对每层都包含文件和目录的多层次目录结构打包
  public static void compressedFiles_Gzip(String folderPath, String targzipFilePath) {
    File srcPath = new File(folderPath);
    int length = srcPath.listFiles().length;
    byte[] buf = new byte[1024]; // 设定读入缓冲区尺寸
    File[] files = srcPath.listFiles();
    try {
      File targetFile = new File(targzipFilePath);
      File parent = targetFile.getParentFile();
      if (!parent.exists()) {
        parent.mkdirs();
      }
      // 建立压缩文件输出流
      FileOutputStream fout = new FileOutputStream(targetFile);
      // 建立tar压缩输出流
      TarOutputStream tout = new TarOutputStream(fout);
      for (int i = 0; i < length; i++) {
        String filename = srcPath.getPath() + File.separator + files[i].getName();
        // 打开需压缩文件作为文件输入流
        FileInputStream fin = new FileInputStream(filename); // filename是文件全路径
        TarEntry tarEn = new TarEntry(files[i]); // 此处必须使用new
        // TarEntry(File
        // file);
        // tarEn.setName(files[i].getName());
        // //此处需重置名称,默认是带全路径的,否则打包后会带全路径
        tout.putNextEntry(tarEn);
        int num;
        while ((num = fin.read(buf)) != -1) {
          tout.write(buf, 0, num);
        }
        tout.closeEntry();
        fin.close();
      }

      tout.close();
      fout.close();

      // 建立压缩文件输出流
      FileOutputStream gzFile = new FileOutputStream(targzipFilePath + ".gz");
      // 建立gzip压缩输出流
      GZIPOutputStream gzout = new GZIPOutputStream(gzFile);
      // 打开需压缩文件作为文件输入流
      FileInputStream tarin = new FileInputStream(targzipFilePath); // targzipFilePath是文件全路径
      int len;
      while ((len = tarin.read(buf)) != -1) {
        gzout.write(buf, 0, len);
      }
      gzout.close();
      gzFile.close();
      tarin.close();
      // 因为只要tar.gz文件,所以删除.tar文件
      del(targzipFilePath);
    } catch (FileNotFoundException e) {
      System.out.println(e);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
Example #27
0
 void f() throws FileNotFoundException, IOException {
   FileInputStream in = new FileInputStream("myfile.txt");
   int b;
   b = in.read();
   while (b != -1) {
     System.out.print((char) b);
     b = in.read();
   }
 }
Example #28
0
  @Override
  public String execute() throws Exception {
    try {

      Map session = ActionContext.getContext().getSession();
      setUser((User) session.get("user"));
      Date date = new Date();
      System.out.println("Time\t\t" + getDeltime() + "\t\t");
      setProduct((Product) getMyDao().getDbsession().get(Product.class, getProductid()));
      getProduct().setUser(getUser());
      getProduct().setName(getPname());
      getProduct().setDelivaryTime(getDeltime());
      getProduct().setDescription(getDesc());
      getProduct().setQty(getQty());
      getProduct().setVat(getVat());
      getProduct().setPrice(getPrice());
      getProduct().setPostage(getPostage());
      getProduct().setUnitsSold(getSold());
      getProduct().setStatus(userEnum.Active.getUserType());
      getProduct().setDate(date);
      getMyDao().getDbsession().update(getProduct());

      if (getImag() != null) {

        byte[] bimg = new byte[(int) getImag().length()];
        byte[] bimg2 = new byte[(int) getImg2().length()];
        byte[] bimg3 = new byte[(int) getImg3().length()];

        FileInputStream flogo = new FileInputStream(getImag());
        FileInputStream fim1 = new FileInputStream(getImg2());
        FileInputStream fim2 = new FileInputStream(getImg3());
        flogo.read(bimg);
        fim1.read(bimg2);
        fim2.read(bimg3);

        setPimg(new Productimage(getProductid(), getProduct()));

        getPimg().setImagefile(bimg);
        getPimg().setImg2(bimg2);
        getPimg().setImg3(bimg3);
        getMyDao().getDbsession().saveOrUpdate(getPimg());
      } else {
      }
      Criteria pro = getMyDao().getDbsession().createCriteria(Product.class);
      pro.add(Restrictions.eq("user", getUser()));
      pro.setMaxResults(50);
      setProdlist((List<Product>) pro.list());
      addActionMessage("Product \t" + getPname() + "\tSuccessfully Updated");

      return "success";
    } catch (Exception e) {
      addActionError("error" + e.getMessage());
      e.printStackTrace();
      return "error";
    }
  }
    public void uploadFile() throws IOException {
      String fileName = url.path().toString();

      DataOutputStream dos = null;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024;

      FileInputStream fileInputStream = new FileInputStream(fileName);

      // Open a HTTP connection to the URL
      request = (HttpURLConnection) url.getUrl().openConnection();
      request.setDoInput(true); // Allow Inputs
      request.setDoOutput(true); // Allow Outputs
      request.setUseCaches(false); // Don't use a Cached Copy
      request.setChunkedStreamingMode(1024);
      request.setRequestMethod("POST");
      request.setRequestProperty("requestection", "Keep-Alive");
      request.setRequestProperty("ENCTYPE", "multipart/form-data");
      request.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      request.setRequestProperty("uploaded_file", fileName);

      dos = new DataOutputStream(request.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes(
          "Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + lineEnd);
      dos.writeBytes(lineEnd);
      // create a buffer of maximum size
      bytesAvailable = fileInputStream.available();

      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // read file and write it into form...
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);

      while (bytesRead > 0) {

        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      // send multipart form data necesssary after file data...
      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
      // close the streams //
      fileInputStream.close();
      dos.flush();
      dos.close();
    }
  /**
   * Checks whether 2 binary files are the same.
   *
   * @param source the source file to copy
   * @param destination the destination file to write
   * @throws FileNotFoundException if the source files don't exist.
   * @throws IOException if there's a problem reading the files.
   */
  @Override
  public boolean isSameFile(File source, File destination) throws IOException {

    if (source.length() != destination.length()) {
      return false;
    }

    FileInputStream fis1 = null;
    FileInputStream fis2 = null;

    try {
      fis1 = new FileInputStream(source);
      fis2 = new FileInputStream(destination);

      byte[] buffer1 = new byte[8192];
      byte[] buffer2 = new byte[8192];

      int read1;
      while ((read1 = fis1.read(buffer1)) != -1) {
        int read2 = 0;
        while (read2 < read1) {
          int n = fis2.read(buffer2, read2, read1 - read2);
          if (n == -1) {
            break;
          }
        }

        if (read2 != read1) {
          return false;
        }

        if (!Arrays.equals(buffer1, buffer2)) {
          return false;
        }
      }
    } finally {
      if (fis2 != null) {
        try {
          fis2.close();
        } catch (IOException e) {
          // ignore
        }
      }
      if (fis1 != null) {
        try {
          fis1.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }

    return true;
  }