コード例 #1
1
  private static void testSysOut(String fs, String exp, Object... args) {
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
      PrintStream saveOut = System.out;
      fos = new FileOutputStream("testSysOut");
      System.setOut(new PrintStream(fos));
      System.out.format(Locale.US, fs, args);
      fos.close();

      fis = new FileInputStream("testSysOut");
      byte[] ba = new byte[exp.length()];
      int len = fis.read(ba);
      String got = new String(ba);
      if (len != ba.length) fail(fs, exp, got);
      ck(fs, exp, got);

      System.setOut(saveOut);
    } catch (FileNotFoundException ex) {
      fail(fs, ex.getClass());
    } catch (IOException ex) {
      fail(fs, ex.getClass());
    } finally {
      try {
        if (fos != null) fos.close();
        if (fis != null) fis.close();
      } catch (IOException ex) {
        fail(fs, ex.getClass());
      }
    }
  }
コード例 #2
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();
        }
      }
    }
  }
コード例 #3
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();
    }
  }
コード例 #4
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;
  }
コード例 #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
ファイル: NetworkFlow.java プロジェクト: gitlw/interviews
  public static void main(String[] args) {
    try {
      Scanner scanner = new Scanner(new FileInputStream("graph.txt"));
      int v = Integer.parseInt(scanner.nextLine());

      int source = Integer.parseInt(scanner.nextLine());

      int sink = Integer.parseInt(scanner.nextLine());

      ListGraph g = new ListGraph(v, source, sink);
      while (scanner.hasNext()) {
        String edgeLine = scanner.nextLine();

        String[] components = edgeLine.split("\\s+");
        assert components.length == 3;
        int i = Integer.parseInt(components[0]);
        int j = Integer.parseInt(components[1]);
        int capacity = Integer.parseInt(components[2]);

        g.addEdge(i, j, capacity);
      }

      System.out.println("Original matrix");
      g.print();

      ListGraph.maxFlow(g);

      g.print();

    } catch (FileNotFoundException e) {
      System.err.println(e.toString());
      System.exit(1);
    }
  }
コード例 #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
  /**
   * 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);
  }
コード例 #9
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();
    }
  }
コード例 #10
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);
  }
コード例 #11
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);
  }
コード例 #12
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;
    }
コード例 #13
0
ファイル: OCSSW.java プロジェクト: mg1989/seadas
  public static boolean downloadOCSSWInstaller() {

    if (isOcsswInstalScriptDownloadSuccessful()) {
      return ocsswInstalScriptDownloadSuccessful;
    }
    try {
      URL website = new URL(OCSSW_INSTALLER_URL);
      ReadableByteChannel rbc = Channels.newChannel(website.openStream());
      FileOutputStream fos = new FileOutputStream(TMP_OCSSW_INSTALLER);
      fos.getChannel().transferFrom(rbc, 0, 1 << 24);
      fos.close();
      (new File(TMP_OCSSW_INSTALLER)).setExecutable(true);
      ocsswInstalScriptDownloadSuccessful = true;
    } catch (MalformedURLException malformedURLException) {
      handleException("URL for downloading install_ocssw.py is not correct!");
    } catch (FileNotFoundException fileNotFoundException) {
      handleException(
          "ocssw installation script failed to download. \n"
              + "Please check network connection or 'seadas.ocssw.root' variable in the 'seadas.config' file. \n"
              + "possible cause of error: "
              + fileNotFoundException.getMessage());
    } catch (IOException ioe) {
      handleException(
          "ocssw installation script failed to download. \n"
              + "Please check network connection or 'seadas.ocssw.root' variable in the \"seadas.config\" file. \n"
              + "possible cause of error: "
              + ioe.getLocalizedMessage());
    } finally {
      return ocsswInstalScriptDownloadSuccessful;
    }
  }
コード例 #14
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();
  }
コード例 #15
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();
		}
	}
コード例 #16
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();
   }
 }
コード例 #17
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;
    }
  }
コード例 #18
0
 private static void writeTokenToFile(String file, TBase token) {
   if (file != null && file.equals("stdout")) {
     System.out.println(token);
   } else {
     OutputStream os = null;
     try {
       os = new FileOutputStream(new File(file));
       os.write(new TSerializer().serialize(token));
     } catch (FileNotFoundException e) {
       System.err.println("Output file not found: " + file + " error: " + e.getMessage());
     } catch (IOException e) {
       System.err.println("Error writing to output file: " + file + " error: " + e.getMessage());
     } catch (TException e) {
       System.err.println("Unable to serialize token to file: " + e.getMessage());
     } finally {
       if (os != null) {
         try {
           os.close();
         } catch (IOException e) {
           // ignore
         }
       }
     }
   }
 }
コード例 #19
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();
       }
     }
 }
コード例 #20
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();
    }
  }
コード例 #21
0
ファイル: A.java プロジェクト: pinguinson/discrete-math-labs
 FastScanner(File f) {
   try {
     br = new BufferedReader(new FileReader(f));
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   }
 }
コード例 #22
0
ファイル: DJ.java プロジェクト: n7jti/artificial_intelligence
  public static void main(String[] args) {
    try {
      InferenceGraph G = new InferenceGraph("hw5.bif");
      Vector nodes = G.get_nodes();
      InferenceGraphNode n = ((InferenceGraphNode) nodes.elementAt(0));
      System.out.println(n.get_name());
      n.get_Prob().print();

      // Create string of variable-value pairs for probability table at node 0*/
      String[][] s = new String[1][2];
      s[0][0] = "B";
      s[0][1] = "False";
      // Compute probability with given variable-value pairs;
      System.out.println(n.get_function_value(s));

      Vector children = n.get_children(); // get_parents() works too;
      for (Enumeration e = children.elements(); e.hasMoreElements(); ) {
        InferenceGraphNode no = (InferenceGraphNode) (e.nextElement());
        System.out.println("\t" + no.get_name());
        no.get_Prob().print(); // Get the probability table object for the node -> Look at
        // ProbabilityFunction.java for info
      }

    } catch (IFException e) {
      System.out.println("Formatting Incorrect " + e.toString());
    } catch (FileNotFoundException e) {
      System.out.println("File not found " + e.toString());
    } catch (IOException e) {
      System.out.println("File not found " + e.toString());
    }
  }
コード例 #23
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;
  }
コード例 #24
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
コード例 #25
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();
    }
  }
コード例 #26
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;
    }
  }
コード例 #27
0
ファイル: ZIP.java プロジェクト: wjlafrance/javaop2
  public static String CreateZip(String[] filesToZip, String zipFileName) {

    byte[] buffer = new byte[18024];

    try {

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      out.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < filesToZip.length; i++) {
        FileInputStream in = new FileInputStream(filesToZip[i]);
        String fileName = null;
        for (int X = filesToZip[i].length() - 1; X >= 0; X--) {
          if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') {
            fileName = filesToZip[i].substring(X + 1);
            break;
          } else if (X == 0) fileName = filesToZip[i];
        }
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        out.closeEntry();
        in.close();
      }
      out.close();
    } catch (IllegalArgumentException e) {
      return "Failed to create zip: " + e.toString();
    } catch (FileNotFoundException e) {
      return "Failed to create zip: " + e.toString();
    } catch (IOException e) {
      return "Failed to create zip: " + e.toString();
    }
    return "Success";
  }
コード例 #28
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;
  }
コード例 #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
 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!!");
   }
 }