コード例 #1
0
 @RequestMapping(value = "download")
 public void download(String id, HttpServletRequest request, HttpServletResponse response) {
   BaseMessage msg = null;
   if (StringUtils.isBlank(id)) {
     return;
   }
   Video video = videoService.queryVideo(id);
   String path = video.getUrl();
   String srcFolderPath = context.getRealPath("/") + path;
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(new File(srcFolderPath));
     // 设置响应头和保存文件名
     //            response.setContentType("APPLICATION/OCTET-STREAM");
     response.addHeader("Content-Length", new File(srcFolderPath).length() + "");
     response.setHeader(
         "Content-Disposition",
         "attachment; filename=\"" + video.getName() + ".mp4" + "\""); // 写出流信息
     int b = 0;
     try {
       OutputStream out = response.getOutputStream();
       while ((b = fis.read()) != -1) {
         out.write(b);
       }
       out.close();
       out.close();
     } catch (FileNotFoundException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }
コード例 #2
0
  static {
    String bibFilePath = testDataParentPath + File.separator + "mhldMergeBibs1346.mrc";
    try {
      RawRecordReader rawRecRdr = new RawRecordReader(new FileInputStream(new File(bibFilePath)));
      while (rawRecRdr.hasNext()) {
        RawRecord rawRec = rawRecRdr.next();
        Record rec = rawRec.getAsRecord(true, false, "999", "MARC8");
        String id = rec.getControlNumber();
        // String id = RecordTestingUtils.getRecordIdFrom001(rec);
        ALL_UNMERGED_BIBS.put(id, rec);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    bibFilePath = testDataParentPath + File.separator + "mhldMerged1346.mrc";
    try {
      RawRecordReader rawRecRdr = new RawRecordReader(new FileInputStream(new File(bibFilePath)));
      while (rawRecRdr.hasNext()) {
        RawRecord rawRec = rawRecRdr.next();
        Record rec = rawRec.getAsRecord(true, false, "999", "MARC8");
        String id = rec.getControlNumber();
        // String id = RecordTestingUtils.getRecordIdFrom001(rec);
        ALL_MERGED_BIB_RESULTS.put(id, rec);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
コード例 #3
0
  public Application(String configurationFile) {
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownListener()));
    Properties props = getPropertiesFromFile(configurationFile);

    try {
      init(props);
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (isErrorFileOutput) {
      try {
        err =
            new BufferedOutputStream(
                new FileOutputStream(
                    ApplicationRegistry.getOutputDirectory()
                        + configurationFile
                        + "."
                        + DateUtils.ts()
                        + ".err.txt"));
        System.setErr(new PrintStream(err));
      } catch (FileNotFoundException e1) {
        e1.printStackTrace();
      }
    }

    if (isOutputFileOutput) {
      try {
        oput =
            new BufferedOutputStream(
                new FileOutputStream(
                    ApplicationRegistry.getOutputDirectory()
                        + configurationFile
                        + "."
                        + DateUtils.ts()
                        + ".txt"));
        System.setOut(new PrintStream(oput));
      } catch (FileNotFoundException e1) {
        e1.printStackTrace();
      }
    }

    try {
      runApplication();
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      finish();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #4
0
  public static void main(String[] args) {
    BufferedReader in;

    try {
      in =
          new BufferedReader(
              new FileReader(
                  "/Users/rahulkhairwar/Documents/IntelliJ IDEA Workspace/Competitive "
                      + "Programming/src/com/google/codejam16/qualificationround/inputB.txt"));

      OutputWriter out = new OutputWriter(System.out);
      Thread thread = new Thread(null, new Solver(in, out), "Solver", 1 << 28);

      thread.start();

      try {
        thread.join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      out.flush();

      in.close();
      out.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #5
0
  private Core() {
    boolean f = false;
    try {
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
        NetworkInterface intf = (NetworkInterface) en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
          InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
            String ipAddress = inetAddress.getHostAddress().toString();
            this.ip = inetAddress;
            f = true;
            break;
          }
        }
        if (f) break;
      }
    } catch (SocketException ex) {
      ex.printStackTrace();
      System.exit(1);
    }
    this.teams = new HashMap<String, Team>();
    this.judges = new HashMap<String, Judge>();
    this.problems = new HashMap<String, ProblemInfo>();
    this.scheduler = new Scheduler();
    this.timer = new ContestTimer(300 * 60);

    try {
      readConfigure();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      System.exit(1);
    }
    this.scoreBoardHttpServer = new ScoreBoardHttpServer(this.scoreBoardPort);
  }
コード例 #6
0
ファイル: NeuralNetwork.java プロジェクト: geomois/ciex2
  // Load a neural network from memory
  public NeuralNetwork loadGenome() {

    // Read from disk using FileInputStream
    FileInputStream f_in = null;
    try {
      f_in = new FileInputStream("./memory/mydriver.mem");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    // Read object using ObjectInputStream
    ObjectInputStream obj_in = null;
    try {
      obj_in = new ObjectInputStream(f_in);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Read an object
    try {
      return (NeuralNetwork) obj_in.readObject();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
コード例 #7
0
ファイル: Query.java プロジェクト: tuanemtv/eibdp
  /** Doc duong dan script */
  public void readScript() {

    FileInputStream fstream;
    try {
      fstream = new FileInputStream(this.get_fileurl());
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null) {
        // Neu bat dau bang select thi moi them vao.
        this.set_getquery(
            this.get_getquery() + strLine + '\n'); // Cong them 1 khoang trang de cau script dung	
        // System.out.println (strLine);
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage());
      e.printStackTrace();
    }
    // Get the object of DataInputStream
    catch (IOException e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage());
      e.printStackTrace();
    }
  }
コード例 #8
0
  public static boolean httpDownload(String httpUrl, String saveFile) {
    // 下载网络文件
    int bytesum = 0;
    int byteread = 0;

    URL url = null;
    try {
      url = new URL(httpUrl);
    } catch (MalformedURLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
      return false;
    }

    try {
      URLConnection conn = url.openConnection();
      InputStream inStream = conn.getInputStream();
      FileOutputStream fs = new FileOutputStream(saveFile);

      byte[] buffer = new byte[1204];
      while ((byteread = inStream.read(buffer)) != -1) {
        bytesum += byteread;
        System.out.println(bytesum);
        fs.write(buffer, 0, byteread);
      }
      return true;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return false;
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }
コード例 #9
0
  public List<SequenciaDidatica> listaDeSequenciaDidatica(String filtro) {

    XStream x = new XStream(new DomDriver());

    int indice = Integer.parseInt(IGEDProperties.getInstance().getPropety("indicesSequencia"));
    String path = IGEDProperties.getInstance().getPropety("sequenciaPath");

    sequenciasDidatica = new ArrayList<SequenciaDidatica>();

    if (filtro.equals("") || filtro == null) {
      try {

        for (int i = 1; i < indice; i++) {

          FileInputStream input = new FileInputStream(path + "/sequencia-" + i + ".xml");

          x.alias("sequenciaDidatica", SequenciaDidatica.class);

          SequenciaDidatica sequencia = (SequenciaDidatica) x.fromXML(input);

          sequenciasDidatica.add(sequencia);
        }

      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return sequenciasDidatica;
  }
コード例 #10
0
  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();
  }
コード例 #11
0
  // 添加一条记录
  public static void addFile(String title, String content, Context context) {
    FileOutputStream fout = null;
    OutputStreamWriter writer = null;
    PrintWriter pw = null;
    try {
      fout = context.openFileOutput(title, context.MODE_PRIVATE);
      writer = new OutputStreamWriter(fout);
      pw = new PrintWriter(writer);
      pw.print(content);
      pw.flush();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } finally {
      if (pw != null) {
        pw.close();
      }
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

      if (fout != null) {
        try {
          fout.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #12
0
 private void init(String testClass, String testName, TestState state) {
   if (writeToFile) {
     File fileToWrite = createFile(testClass, testName);
     if (fileToWrite == null) {
       System.err.println(
           "Cannot create file for " + testClass + "." + testName + ". Writing to STDOUT");
       state.printStream = System.out;
     } else {
       try {
         state.printStream = new PrintStream(new FileOutputStream(fileToWrite));
         System.out.println(
             testClass + "." + testName + " writing to " + fileToWrite.getAbsolutePath());
       } catch (FileNotFoundException e) {
         e.printStackTrace();
         state.printStream = System.out;
       }
     }
   } else {
     state.printStream = System.out;
   }
   // sanity check
   if (state.printStream == null) {
     throw new IllegalStateException("PrintStream cannot be null!!");
   }
 }
コード例 #13
0
 private void executeAllScriptsInDirectory(
     File dir, boolean recurseDown, int maxDepth, int currentDepth) {
   if (dir.isDirectory()) {
     for (File file : dir.listFiles()) {
       if (file.isDirectory() && recurseDown && maxDepth > currentDepth) {
         if (Config.SCRIPT_DEBUG) {
           _log.info("Entering folder: " + file.getName());
         }
         this.executeAllScriptsInDirectory(file, recurseDown, maxDepth, currentDepth + 1);
       } else if (file.isFile()) {
         try {
           String name = file.getName();
           int lastIndex = name.lastIndexOf('.');
           String extension;
           if (lastIndex != -1) {
             extension = name.substring(lastIndex + 1);
             ScriptEngine engine = getEngineByExtension(extension);
             if (engine != null) {
               this.executeScript(engine, file);
             }
           }
         } catch (FileNotFoundException e) {
           // should never happen
           e.printStackTrace();
         } catch (ScriptException e) {
           reportScriptFileError(file, e);
           // e.printStackTrace();
         }
       }
     }
   } else
     throw new IllegalArgumentException(
         "The argument directory either doesnt exists or is not an directory.");
 }
コード例 #14
0
 public static void unzipIntoDirectory(File file, File directory) {
   try {
     unzipIntoDirectory(new FileInputStream(file), directory);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }
コード例 #15
0
ファイル: Flexc1.java プロジェクト: soheean/JAVA
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    File file = new File("Exp6_Gis.txt");
    BufferedReader reader = null;
    String tempString = null;
    int line = 1;

    try {
      System.out.println("以行为单位读取文件内容,一次读一整行:");
      reader = new BufferedReader(new FileReader(file));
      while ((tempString = reader.readLine()) != null) {
        System.out.println("Line" + line + ":" + tempString);
        line++;
      }
      reader.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
コード例 #16
0
ファイル: MarkingCode.java プロジェクト: mabedilhadi/java
  private void save_buttonActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_save_buttonActionPerformed
    for (int i = 0; i < rubric_table.getColumnCount(); i++) {
      try {
        GradeAccess.enterGrade(
            studentID,
            courseID,
            actName,
            rubric_table.getModel().getValueAt(i, 0).toString(),
            Float.parseFloat(rubric_table.getModel().getValueAt(i, 1).toString()));
      } catch (NumberFormatException e) {
        e.printStackTrace();
      } catch (SQLException e) {
        GradeAccess.updateGrade(
            studentID,
            courseID,
            actName,
            rubric_table.getModel().getValueAt(i, 0).toString(),
            Float.parseFloat(rubric_table.getModel().getValueAt(i, 1).toString()));
      }
    }

    try {
      PrintWriter out = new PrintWriter(paths[0] + "/" + studentID + "/" + actName + ".py");
      out.write(submission_text_area.getText());
      out.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    setOkToNav();
    JOptionPane.showMessageDialog(this, "Grade and comments saved.");
  } // GEN-LAST:event_save_buttonActionPerformed
コード例 #17
0
ファイル: GraphTraversal.java プロジェクト: rbrsmith/JavaFun
  /**
   * @param fname String filename to read matrix from
   * @return Map of lists, 1 indexed representing the adjacency matrix
   */
  public Map<Integer, List<Integer>> readAdjacencyMatrix(String fname) {
    Map<Integer, List<Integer>> adjMatrix = new HashMap<>();
    int i = 1;

    try {
      BufferedReader br = new BufferedReader(new FileReader(fname));
      String line;
      while ((line = br.readLine()) != null) {
        List<String> words = Arrays.asList(line.split("\\s*"));
        List<Integer> wordVals = new ArrayList<>();
        for (String w : words) {
          if (w.equals("1") || w.equals("0")) {
            wordVals.add(Integer.parseInt(w));
          }
        }
        adjMatrix.put(i, wordVals);
        i += 1;
      }
      br.close();
      return adjMatrix;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return null;
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #18
0
    @Override
    protected Void doInBackground(ArrayList... params) {
      try {
        String fileLocation = String.valueOf(params[0].get(0));
        String fileName = String.valueOf(params[0].get(1));
        String folder = String.valueOf(params[0].get(2));

        String path = Constants.ASSETS_IP + fileLocation + fileName;
        URL u = new URL(path);
        HttpParams httpParameters = new BasicHttpParams();
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        int timeoutConnection = 3000;
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

        InputStream is = c.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File(folder + "/" + fileName));
        int bytesRead = 0;
        byte[] buffer = new byte[4096];
        while ((bytesRead = is.read(buffer)) != -1) {
          fos.write(buffer, 0, bytesRead);
        }
        fos.close();
        is.close();
        c.disconnect();
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return null;
    }
コード例 #19
0
	/*
	*	Constructor (class entry point from java)
	*
	*/
	CDToolParser(String infilename, String outfile){
		try{
			//@ToDo make outfile stream, this prints to System.out instead
			out=System.out;
			
			
			unparsed_lines = new ArrayList<String>();
			//spectral_entries = new ArrayList<SpectralEntry>();
			spectral_table = new ArrayList<String>();

			//File f = new File(infilename);
			FileInputStream fis= new FileInputStream(infilename);
			InputStreamReader isr = new InputStreamReader((InputStream)fis);
			BufferedReader br = new BufferedReader((Reader)isr);
			String line="";
			while((line=br.readLine())!=null){
				String p=ParseLine(line);
			}
			WriteExported();
			
		}catch(FileNotFoundException fnfe){
			fnfe.printStackTrace();
		}catch(IOException ioe){
			ioe.printStackTrace();
		}
	}
コード例 #20
0
  /**
   * Read the topic distribution from the file
   *
   * @param fp
   * @return
   */
  public static Map<String, List<Double>> readTopicDist(String fp) {
    Map<String, List<Double>> res = new HashMap<String, List<Double>>();

    if (fp == null || fp.length() == 0) return res;

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp))));

      String line = null;

      while ((line = reader.readLine()) != null) {
        String[] fields = line.split(" ");
        int userid = Integer.parseInt(fields[0]);
        int queryid = Integer.parseInt(fields[1]);

        List<Double> probs = new ArrayList<Double>();
        for (int i = 2; i < fields.length; i++) {
          probs.add(Double.parseDouble(fields[i].split(":")[1]));
        }

        res.put(userid + "-" + queryid, probs);
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(res);
  }
コード例 #21
0
ファイル: Bot.java プロジェクト: dims12/program-ab
 /**
  * write categories to AIMLIF file
  *
  * @param cats array list of categories
  * @param filename AIMLIF filename
  */
 public void writeIFCategories(ArrayList<Category> cats, String filename) {
   // System.out.println("writeIFCategories "+filename);
   BufferedWriter bw = null;
   File existsPath = new File(aimlif_path);
   if (existsPath.exists())
     try {
       // Construct the bw object
       bw = new BufferedWriter(new FileWriter(aimlif_path + "/" + filename));
       for (Category category : cats) {
         bw.write(Category.categoryToIF(category));
         bw.newLine();
       }
     } catch (FileNotFoundException ex) {
       ex.printStackTrace();
     } catch (IOException ex) {
       ex.printStackTrace();
     } finally {
       // Close the bw
       try {
         if (bw != null) {
           bw.flush();
           bw.close();
         }
       } catch (IOException ex) {
         ex.printStackTrace();
       }
     }
 }
コード例 #22
0
  /**
   * read the transition matrix from the file
   *
   * @param fp
   * @return
   */
  public static Map<Integer, Set<Integer>> readTransitionMatrix(String fp) {
    Map<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>();

    if (fp == null || fp.length() == 0) return res;

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp))));

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] fields = line.split(" ");
        int from = Integer.parseInt(fields[0]);
        int to = Integer.parseInt(fields[1]);

        if (res.containsKey(from)) {
          res.get(from).add(to);
        } else {
          Set<Integer> cset = new HashSet<Integer>();
          cset.add(to);

          res.put(from, cset);
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(res);
  }
コード例 #23
0
ファイル: A.java プロジェクト: pinguinson/discrete-math-labs
 FastScanner(File f) {
   try {
     br = new BufferedReader(new FileReader(f));
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }
コード例 #24
0
  /**
   * Read the topic-document relations
   *
   * @param fp
   * @return
   */
  public static Map<Integer, Set<Integer>> readTopicDocuments(String fp) {
    Map<Integer, Set<Integer>> res = new HashMap<Integer, Set<Integer>>();

    if (fp == null || fp.length() == 0) return res;

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(fp))));

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] fields = line.split(" ");
        int docid = Integer.parseInt(fields[0]);
        int classid = Integer.parseInt(fields[1]);

        if (res.containsKey(classid)) {
          res.get(classid).add(docid);
        } else {
          Set<Integer> cset = new HashSet<Integer>();
          cset.add(docid);

          res.put(classid, cset);
        }
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return Collections.unmodifiableMap(res);
  }
コード例 #25
0
  public static Map<String, String> readProperties(InputStream inputStream) {
    Map<String, String> propertiesMap = null;
    try {
      propertiesMap = new LinkedHashMap<String, String>();

      Properties properties = new Properties();
      properties.load(inputStream);

      Enumeration<?> enumeration = properties.propertyNames();
      while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        String value = (String) properties.get(key);
        propertiesMap.put(key, value);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return propertiesMap;
  }
コード例 #26
0
ファイル: Converter.java プロジェクト: sokolek/ai2013
  public void convertIndexToBin(int word) {
    File indexTextFile = new File(WebCBIR.baseFolder, "index/" + word + ".txt");
    File indexBinFile = new File(WebCBIR.baseFolder, "index/" + word + ".bin");
    DataOutputStream dos = null;
    try {
      dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(indexBinFile)));
    } catch (FileNotFoundException e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    Scanner scanner = null;
    try {
      scanner = new Scanner(indexTextFile, "UTF-8");
      int cluster = scanner.nextInt();
      if (cluster != word) {
        scanner.close();
        return;
      }
      int numberOfEntries = scanner.nextInt();
      dos.writeInt(cluster);
      dos.writeInt(numberOfEntries);
      for (int i = 0; i < numberOfEntries; i++) {
        dos.writeShort(scanner.nextInt());
      }
      scanner.close();
      dos.close();
    } catch (Exception ex) {
      ex.printStackTrace();
      if (scanner != null) scanner.close();
    }
  }
コード例 #27
0
ファイル: Server.java プロジェクト: piyushagade/BitSync
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
コード例 #28
0
ファイル: Converter.java プロジェクト: sokolek/ai2013
 public void convertWeightsToBin() {
   File weightsTextFile = new File(WebCBIR.baseFolder, "index/weights-idf.txt");
   File weightsBinFile = new File(WebCBIR.baseFolder, "index/weights-idf.bin");
   DataOutputStream dos = null;
   try {
     dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(weightsBinFile)));
   } catch (FileNotFoundException e) {
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   }
   Scanner scanner = null;
   try {
     scanner = new Scanner(weightsTextFile, "UTF-8");
     int featureCount = scanner.nextInt();
     dos.writeInt(featureCount);
     for (int i = 0; i < featureCount; i++) {
       String val = scanner.next();
       float idf = Float.parseFloat(val);
       dos.writeFloat(idf);
     }
     scanner.close();
     dos.close();
   } catch (Exception ex) {
     ex.printStackTrace();
     if (scanner != null) scanner.close();
   }
 }
コード例 #29
0
  public void processFile(String inputFileName) {

    try {
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(new FileInputStream(new File(inputFileName))));
      String[] headers = reader.readLine().split(SEPARATOR);

      for (String s : headers) {
        attrByValue.put(s, new HashSet<String>());
      }

      String line = null;
      while ((line = reader.readLine()) != null) {
        String[] columnValues = line.split(SEPARATOR);
        if (columnValues.length != headers.length) {
          System.err.println("There is a huge problem with data file");
        }

        for (int i = 0; i < columnValues.length; i++) {
          attrByValue.get(headers[i]).add(columnValues[i]);
        }
      }

      reader.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #30
0
  public BookCatalogImpl() {

    try {

      final String filePath = path + "catalog.json";
      // read the json file
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      InputStream inputStream = classLoader.getResourceAsStream(filePath);

      BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
      bookStrBuilder = new StringBuilder();

      String inputStr;
      while ((inputStr = streamReader.readLine()) != null) bookStrBuilder.append(inputStr);

      final ObjectMapper mapper = new ObjectMapper();

      catalog = mapper.readValue(bookStrBuilder.toString(), new TypeReference<List<Book>>() {});

      hBookDetails = new Hashtable();

      for (Book book : catalog) {

        hBookDetails.put(book.getId(), book);
      }

    } catch (FileNotFoundException ex) {
      ex.printStackTrace();
    } catch (IOException ex) {
      ex.printStackTrace();
    } catch (NullPointerException ex) {
      ex.printStackTrace();
    }
  }