コード例 #1
1
  public static void execute(String[] args) {

    try {

      String hs2mmFile = args[0];
      HashMap human2mouse = human2mouse(hs2mmFile);
      String inputFile = args[1];
      String outputFile = args[2];
      FileWriter fwriter = new FileWriter(outputFile);
      BufferedWriter out = new BufferedWriter(fwriter);

      FileInputStream fstream = new FileInputStream(inputFile);
      DataInputStream din = new DataInputStream(fstream);
      BufferedReader in = new BufferedReader(new InputStreamReader(din));
      while (in.ready()) {
        String str = in.readLine();
        String[] split = str.split("\t");
        out.write(split[0] + "\t" + split[1]);
        for (int i = 2; i < split.length; i++) {
          if (human2mouse.containsKey(split[i])) {
            out.write("\t" + (String) human2mouse.get(split[i]));
          }
        }
        out.write("\n");
      }
      in.close();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
ファイル: Graph.java プロジェクト: ajurcik/oit4cb
 private void writeCSR(int[] rows, int[] columns) throws IOException {
   try (BufferedWriter writer = new BufferedWriter(new FileWriter("CSR.txt"))) {
     writer.append("R: ");
     for (int i = 0; i < rows.length; i++) {
       writer.append(String.format("%4d ", rows[i]));
     }
     writer.newLine();
     writer.append("C: ");
     for (int i = 0; i < columns.length; i++) {
       writer.append(String.format("%4d ", columns[i]));
     }
     writer.newLine();
     writer.newLine();
     // write graph neighbors
     for (int i = 0; i < rows.length - 1; i++) {
       int start = rows[i];
       int end = rows[i + 1];
       writer.append(String.format("%4d: ", i));
       for (int j = start; j < end; j++) {
         writer.append(String.format("%4d ", columns[j]));
       }
       writer.newLine();
     }
   }
 }
  public static void main(String[] args) throws Exception {

    /*  BufferedReader br=new BufferedReader(new FileReader("input.txt"));
        BufferedWriter out=new BufferedWriter(new FileWriter("output.txt"));
    */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 2000);
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out), 2000);
    String[] s = br.readLine().split(" ");
    int n = Integer.parseInt(s[0]);
    int q = Integer.parseInt(s[1]);
    int num[] = new int[n + 1];
    int[] m = new int[3 * n + 1]; // size = 2*n+1
    Arrays.fill(num, -1);
    s = br.readLine().split(" ");
    for (int i = 1; i <= n; i++) num[i] = Integer.parseInt(s[i - 1]);
    /// build tree
    maketree(1, 1, n, m, num);

    for (int qq = 1; qq <= q; qq++) {
      s = br.readLine().split(" ");
      int i = Integer.parseInt(s[0]);
      int j = Integer.parseInt(s[1]);
      int ans = query(1, 1, n, m, num, i, j);
      out.write("" + num[ans] + "\n");
      out.flush();
    }
  }
コード例 #4
0
  public void save(T media) throws IOException {

    if (!canSaveType(media.getClass())) {
      return;
    }

    String preName = media.getPreviousName();
    File f = null;

    if (fileCache.containsKey(media)) {
      f = fileCache.get(media);
    } else {
      f = generateSaveFile(media);
    }

    Gson gson =
        new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create();
    media.setSaved(true);
    String json = gson.toJson(media);

    BufferedWriter bfw = new BufferedWriter(new FileWriter(f));
    bfw.write(json);
    bfw.close();

    if (MediaBase.class.isAssignableFrom(media.getClass())) {
      ((MediaBase) media).save();
      System.out.println("Thumb saved");
    }

    if (preName != null && !preName.equals(media.getSaveString())) {
      deleteOldVersion(media, preName);
    }
  }
コード例 #5
0
ファイル: main.java プロジェクト: davidhmhernandez/AcesoDatos
  /** Metodo que escribe el nombre de los Futbolistas separados por coma y punto */
  private static void escribirFutbolistas() {
    FileWriter fw = null;
    try {
      fw = new FileWriter(nombrefichero2);
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    BufferedWriter bf = new BufferedWriter(fw);

    try {
      for (int i = 0; i < futbolistas.length; i++) {
        bf.write(futbolistas[i] + "." + ",");
      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      try {
        bf.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
コード例 #6
0
ファイル: VlcCrashHandler.java プロジェクト: JokeLook/YiYuan
  private void writeLogcat(String name) {
    CharSequence timestamp = DateFormat.format("yyyyMMdd_kkmmss", System.currentTimeMillis());
    String filename = name + "_" + timestamp + ".log";
    String[] args = {"logcat", "-v", "time", "-d"};

    try {
      Process process = Runtime.getRuntime().exec(args);
      InputStreamReader input = new InputStreamReader(process.getInputStream());
      OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(filename));
      BufferedReader br = new BufferedReader(input);
      BufferedWriter bw = new BufferedWriter(output);
      String line;

      while ((line = br.readLine()) != null) {
        bw.write(line);
        bw.newLine();
      }

      bw.close();
      output.close();
      br.close();
      input.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #7
0
  // Starts redirection of streams.
  public void run() {
    BufferedReader r = new BufferedReader(new InputStreamReader(in), 1);
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out));
    byte[] buf = new byte[256];

    try {
      String line;

      /* This is to check that the distant vm has started,
       * if such a vm has been provided at construction :
       * - As soon as we can read something from r BufferedReader,
       *   that means the distant vm is already started.
       * Thus we signal associated JavaVM object that it is now started.
       */
      if (((line = r.readLine()) != null) && (javaVM != null)) {
        javaVM.setStarted();
      }

      // Redirects r on w.
      while (line != null) {
        w.write(preamble);
        w.write(line);
        w.newLine();
        w.flush();
        line = r.readLine();
      }

    } catch (IOException e) {
      System.err.println("*** IOException in StreamPipe.run:");
      e.printStackTrace();
    }
  }
コード例 #8
0
ファイル: FileUtils.java プロジェクト: sinoace/Library
 /**
  * 把给定的字符串写到给定的文件中并使用给定的字符集编码
  *
  * @param file 给定的文件
  * @param string 给定的字符串
  * @param charset 给定的字符集
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeString(File file, String string, Charset charset, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, charset, isAppend);
   bw.write(string);
   bw.flush();
   bw.close();
 }
コード例 #9
0
ファイル: Installer.java プロジェクト: suever/CTP
 private void setFileText(File file, String text) throws Exception {
   BufferedWriter bw =
       new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
   bw.write(text, 0, text.length());
   bw.flush();
   bw.close();
 }
コード例 #10
0
ファイル: NouveauPanel.java プロジェクト: Philippe-Ch/ZPendu
  public void ecrireFichier(String nomFic, String texte) {
    // on va chercher le chemin et le nom du fichier et on me tout ca dans un String
    String adressedufichier = System.getProperty("user.dir") + "/" + nomFic;

    // on met try si jamais il y a une exception
    try {
      /**
       * BufferedWriter a besoin d un FileWriter, les 2 vont ensemble, on donne comme argument le
       * nom du fichier true signifie qu on ajoute dans le fichier (append), on ne marque pas par
       * dessus
       */
      FileWriter fw = new FileWriter(adressedufichier, true);

      // le BufferedWriter output auquel on donne comme argument le FileWriter fw cree juste au
      // dessus
      BufferedWriter output = new BufferedWriter(fw);

      // on marque dans le fichier ou plutot dans le BufferedWriter qui sert comme un tampon(stream)
      output.write(texte);
      // on peut utiliser plusieurs fois methode write

      output.flush();
      // ensuite flush envoie dans le fichier, ne pas oublier cette methode pour le BufferedWriter

      output.close();
      // et on le ferme
    } catch (IOException ioe) {
      System.out.print("Erreur : ");
      ioe.printStackTrace();
    }
  }
コード例 #11
0
  public void testCollect() throws Exception {
    Path p = new Path(this.ROOT_DIR, "rankfile");

    FSDataOutputStream o = this.getFileSystem().create(p);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(o));
    bw.write("209.191.139.200\n");
    bw.write("twelve\n");
    bw.close();

    String jarFile;
    jarFile = GenericUDFGeoIP.class.getProtectionDomain().getCodeSource().getLocation().getFile();
    client.execute("add jar " + jarFile);
    jarFile =
        com.maxmind.geoip.LookupService.class
            .getProtectionDomain()
            .getCodeSource()
            .getLocation()
            .getFile();
    client.execute("add jar " + jarFile);
    // download this or put in reasources
    client.execute(" add file /tmp/GeoIP.dat");

    client.execute(
        "create temporary function geoip as 'com.jointhegrid.udf.geoip.GenericUDFGeoIP'");
    client.execute(
        "create table  ips  ( ip string) row format delimited fields terminated by '09' lines terminated by '10'");
    client.execute("load data local inpath '" + p.toString() + "' into table ips");

    client.execute("select geoip(ip, 'COUNTRY_NAME', './GeoIP.dat') FROM ips");
    List<String> expected = Arrays.asList("United States", "N/A");
    assertEquals(expected, client.fetchAll());

    client.execute("drop table ips");
  }
コード例 #12
0
 /** Writes timeBin2PersonId2UserGroup2CausedDelay */
 private void writeHourlyCausedDelayForEachPerson() {
   SortedMap<Double, Map<Id<Person>, Double>> timeBin2CausingPerson2Delay =
       getCausingPersonDelay(noOfTimeBins);
   BufferedWriter writer =
       IOUtils.getBufferedWriter(
           runDir
               + "/analysis/timeBin2Person2UserGroup2CausedDelay_"
               + pricingScenario
               + suffixForSoring
               + ".txt");
   try {
     writer.write("timeBin \t personId \t userGroup \t delayInSec \n");
     for (double d : timeBin2CausingPerson2Delay.keySet()) {
       for (Id<Person> personId : timeBin2CausingPerson2Delay.get(d).keySet()) {
         writer.write(
             d
                 + "\t"
                 + personId
                 + "\t"
                 + pf.getMunichUserGroupFromPersonId(personId)
                 + "\t"
                 + timeBin2CausingPerson2Delay.get(d).get(personId)
                 + "\n");
       }
     }
     writer.close();
   } catch (Exception e) {
     throw new RuntimeException("Data is not written in file. Reason: " + e);
   }
 }
  @Test
  public void testRedirectionCycle() throws IOException, XMLStreamException {
    // source dump
    File tmpSrcDump = File.createTempFile("wiki-src-dump", "xml");
    File tmpTargetDump = File.createTempFile("wiki-target-dump", "xml");

    // base structure - "<mediawiki><page><title></title><id><id></page></mediawiki>"
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmpSrcDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "</page>"
            + "<page>"
            + "<title>Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "</page>"
            + "</mediawiki>");
    bw.close();

    bw = new BufferedWriter(new FileWriter(tmpTargetDump));
    bw.write(
        "<mediawiki>"
            + "<page>"
            + "<title>Test1</title>"
            + "<id>1</id>"
            + "<redirect/>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">#REDIRECT [[Test3]] {{R from CamelCase}}</text>"
            + "</revision>"
            + "</page>"
            + "<page>"
            + "<title>NEW_Test2</title>"
            + "<id>2</id>"
            + "</page>"
            + "<page>"
            + "<title>Test3</title>"
            + "<id>3</id>"
            + "<redirect/>"
            + "<revision>"
            + "<id>1234556</id>"
            + "<text xml:space=\"preserve\">#REDIRECT [[Test1]] {{R from CamelCase}}</text>"
            + "</revision>"
            + "</page>"
            + "</mediawiki>");
    bw.close();
    Map<String, String> hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump);
    assertEquals(3, hshResults.size());
    // Test1 REDIRECTS TO Test3, but since it forms a cycle, Test1 is mapped to itself
    assertEquals(true, !hshResults.get("Test1").equals("Test3"));

    tmpSrcDump.delete();
    tmpTargetDump.delete();
  }
  @SuppressWarnings("ResultOfMethodCallIgnored")
  @Test
  public void testUnchangedPageEntries() throws IOException, XMLStreamException {
    // source dump
    File tmpSrcDump = File.createTempFile("wiki-src-dump", "xml");
    File tmpTargetDump = File.createTempFile("wiki-target-dump", "xml");

    // base structure - "<mediawiki><page><title></title><id><id></page></mediawiki>"
    BufferedWriter bw = new BufferedWriter(new FileWriter(tmpSrcDump));
    bw.write(
        "<mediawiki><page><title>Test1</title><id>1</id></page><page><title>Test2</title><id>2</id></page></mediawiki>");
    bw.close();

    bw = new BufferedWriter(new FileWriter(tmpTargetDump));
    bw.write(
        "<mediawiki><page><title>Test1</title><id>1</id></page><page><title>Test2</title><id>2</id></page></mediawiki>");
    bw.close();

    // default diff will also include all unchanged entries
    Map<String, String> hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump);
    assertEquals(2, hshResults.size());

    // setting the flag to false will include unchanged entries
    hshResults = WikipediaRevisionMapper.map(tmpSrcDump, tmpTargetDump, false);
    assertEquals(0, hshResults.size());
    // remove tmp files
    tmpSrcDump.delete();
    tmpTargetDump.delete();
  }
コード例 #15
0
ファイル: Infobox.java プロジェクト: woo88/myProject
  private static void convertInsToCatInner(
      String baseDir, String fileName, BufferedWriter writer, Map<String, String> insToCat)
      throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(baseDir + fileName)));
    int lineNumber = 0;
    int totalLineNumber = 0;
    String inputLine = null;
    System.out.println("Start reading: " + baseDir + fileName);
    while ((inputLine = reader.readLine()) != null) {
      // check progress
      if (lineNumber >= 500000) {
        totalLineNumber += lineNumber;
        lineNumber = 0;
        System.out.print(totalLineNumber + ", ");
      }
      lineNumber++;

      // ignore comment lines.
      if (inputLine.startsWith("#")) continue;

      // tokenize
      String[] strArr = inputLine.split(" ");
      String ins = App.removePrefix(strArr[0], "/resource/");

      try {
        writer.write(insToCat.get(ins));
        writer.newLine();
      } catch (NullPointerException e) {
        continue;
      }
    }
    reader.close();
    System.out.println("Done");
  }
コード例 #16
0
ファイル: FileUtils.java プロジェクト: sinoace/Library
 /**
  * 把给定的字符数组写到给定的文件中
  *
  * @param file 给定的文件中
  * @param chars 给定的字符数组
  * @param off 偏移量,从字符数组的此处开始获取数据写到文件中去
  * @param length 要写出的字符数
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeChar(File file, char[] chars, long off, int length, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, isAppend);
   IOUtils.write(bw, chars, off, length);
   bw.flush();
   bw.close();
 }
コード例 #17
0
ファイル: FileUtils.java プロジェクト: sinoace/Library
 /**
  * 把给定的字符数组写到给定的文件中并使用给定的字符集编码
  *
  * @param file 给定的文件中
  * @param chars 给定的字符数组
  * @param charset 给定的字符集
  * @param isAppend 是否追加到文件末尾
  * @throws IOException
  */
 public static void writeChar(File file, char[] chars, Charset charset, boolean isAppend)
     throws IOException {
   BufferedWriter bw = IOUtils.openBufferedWriter(file, charset, isAppend);
   IOUtils.write(bw, chars);
   bw.flush();
   bw.close();
 }
コード例 #18
0
 public static void main(String[] args) throws IOException {
   String str = "hai friends";
   FileWriter fw = new FileWriter("textfile1.txt", false);
   BufferedWriter bw = new BufferedWriter(fw);
   for (int i = 0; i < str.length(); i++) bw.write(str.charAt(i));
   bw.close();
 }
コード例 #19
0
  static void writeNewData(String datafile) {

    try {
      BufferedReader bufr = new BufferedReader(new FileReader(datafile));
      BufferedWriter bufw = new BufferedWriter(new FileWriter(datafile + ".nzf"));

      String line;
      String[] tokens;

      while ((line = bufr.readLine()) != null) {

        tokens = line.split(" ");
        bufw.write(tokens[0]);
        for (int i = 1; i < tokens.length; i++) {

          Integer index = Integer.valueOf(tokens[i].split(":")[0]);
          if (nnzFeas.contains(index)) {
            bufw.write(" " + tokens[i]);
          }
        }
        bufw.newLine();
      }
      bufw.close();
      bufr.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(0);
    }
  }
コード例 #20
0
 public static void createBoltIdentifyingFiles(TopologyContext topologyContext) {
   String componentName = topologyContext.getThisComponentId();
   Long ts = System.currentTimeMillis();
   String fileName = "bolt-" + ts + "-" + componentName + ".log";
   File file =
       new File(
           in.dream_lab.stream.eventgen.utils.GlobalConstants.defaultBoltDirectory + fileName);
   try {
     FileWriter fw = new FileWriter(file);
     BufferedWriter bw = new BufferedWriter(fw);
     String rowString =
         InetAddress.getLocalHost().getHostName()
             + ","
             + Thread.currentThread().getName()
             + ","
             + componentName
             + ","
             + ts;
     bw.write(rowString);
     bw.flush();
     bw.close();
   } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
コード例 #21
0
ファイル: ColorHist.java プロジェクト: SeanNguyen/cs2108
  public static void preprocess(Map<String, ImageData> images) throws IOException {
    File cacheFile = new File(colorHistCacheFile);
    if (cacheFile.exists()) {
      try (BufferedReader br = new BufferedReader(new FileReader(colorHistCacheFile))) {
        String line = br.readLine();

        while (line != null) {
          double[] bins = new double[dim * dim * dim];
          String key = line.substring(0, line.indexOf(" "));
          String values = line.substring(line.indexOf("[") + 1, line.indexOf("]"));
          String binS[] = values.split(",\\s");
          for (int i = 0; i < binS.length; i++) {
            bins[i] = Double.parseDouble(binS[i]);
          }
          images.get(key).setColorHistogram(bins);
          line = br.readLine();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      try (BufferedWriter bw = new BufferedWriter(new FileWriter(colorHistCacheFile))) {
        for (ImageData id : images.values()) {
          double[] colorHistogram = getHist(id);
          id.setColorHistogram(colorHistogram);

          String line = String.format("%s %s%n", id.getFilename(), Arrays.toString(colorHistogram));
          bw.write(line);
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #22
0
  private static void startLeg(final Leg leg, final BufferedWriter out) throws IOException {
    out.write("\t\t\t<leg mode=\"");
    out.write(leg.getMode());
    out.write("\"");
    if (leg.getDepartureTime() != Time.UNDEFINED_TIME) {
      out.write(" dep_time=\"");
      out.write(Time.writeTime(leg.getDepartureTime()));
      out.write("\"");
    }
    if (leg.getTravelTime() != Time.UNDEFINED_TIME) {
      out.write(" trav_time=\"");
      out.write(Time.writeTime(leg.getTravelTime()));
      out.write("\"");
    }
    //		if (leg instanceof LegImpl) {
    //			LegImpl l = (LegImpl)leg;
    //			if (l.getDepartureTime() + l.getTravelTime() != Time.UNDEFINED_TIME) {
    //				out.write(" arr_time=\"");
    //				out.write(Time.writeTime(l.getDepartureTime() + l.getTravelTime()));
    //				out.write("\"");
    //			}
    //		}
    // arrival time is in dtd, but no longer evaluated in code (according to not being in API).
    // kai, jun'16

    out.write(">\n");
  }
コード例 #23
0
 private static void doWriteToLogFile(
     final String json, final SimpleDateFormat sdf, final BufferedWriter out) throws IOException {
   out.write(sdf.format(new Date()));
   out.write(" [AnalyticaProcess] - ");
   out.write(json);
   out.write("\n");
 }
コード例 #24
0
  public static void main(String[] args) {
    while (true) {
      File file = new File("src/wifi_14.iwl");
      if (file.exists()) {
        System.out.println("si existe este archivo");
      } else {
        System.out.println("No existe");
      }
      BufferedWriter bw = null;
      try {
        bw = new BufferedWriter(new FileWriter(file, true));
        System.out.println("Escriba en el archivo :" + file.getName());
        String content = "\n" + "Nueva Linea_____Extrema" + (int) (Math.random() * 100000000);
        bw.write(content);
      } catch (Exception e) {
        System.out.println("Error al leer el archivo:" + e.getMessage());
      } finally {
        if (bw != null) {
          try {
            bw.close();
          } catch (IOException ex) {
            System.out.println("Error..." + ex.getMessage());
          }
        }
      }

      /// Espera :)
      try {

        Thread.sleep(1000);
      } catch (InterruptedException ex) {
        Logger.getLogger(WriteCoordenadas.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
コード例 #25
0
  void stopRecord() {
    recording = false;
    sendBroadcast(new Intent(C.actionSetIconRecord));
    try {
      mW.flush();
      mW.close();
      mW = null;

      // http://stackoverflow.com/questions/13737261/nexus-4-not-showing-files-via-mtp
      //			MediaScannerConnection.scanFile(this, new String[] { mFile.getAbsolutePath() }, null,
      // null);
      // http://stackoverflow.com/questions/5739140/mediascannerconnection-produces-android-app-serviceconnectionleaked
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE).setData(Uri.fromFile(mFile)));

      Toast.makeText(
              this,
              new StringBuilder()
                  .append(getString(R.string.app_name))
                  .append("Record-")
                  .append(getDate())
                  .append(".csv ")
                  .append(getString(R.string.notify_toast_saved)),
              Toast.LENGTH_LONG)
          .show();
    } catch (Exception e) {
      e.printStackTrace();
      Toast.makeText(
              this,
              getString(R.string.notify_toast_error) + " " + e.getMessage(),
              Toast.LENGTH_LONG)
          .show();
    }
    topRow = true;
    mNM.notify(10, mNotificationRead);
  }
コード例 #26
0
ファイル: VizsterServer.java プロジェクト: arumshisky/knowevo
  public void run() {
    try {
      DataInputStream in = new DataInputStream(sockd.getInputStream());
      DataOutputStream out = new DataOutputStream(sockd.getOutputStream());

      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      vdb.setBw(bw);

      String name;

      while ((name = br.readLine()) != null) {
        System.out.println("graph for " + name);
        vdb.buildGraph(name, max_depth, peers_only);
        vdb.convertGraph();
        System.out.println("graph for " + name + " is ready");
        break;
      }

      br.close();
      in.close();
      bw.close();
      out.close();

      sockd.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #27
0
  /**
   * 将用户提交的简介写入html文件中, 并将文件的url设置进的htmlurl属性中
   *
   * @param request
   * @param choicenesscontent
   * @throws IOException
   */
  private void saveHtmlUrl(HttpServletRequest request, YztChoicenesscontent choicenesscontent)
      throws IOException {
    // 保存简介的html
    String introduction = choicenesscontent.getIntroduction();

    String htmlStr =
        "<!DOCTYPE html><head><meta charset=\"UTF-8\"><title>内容简介</title></head><body>"
            + introduction
            + "</body></html>";

    /* String htmlStr = choicenesscontent.getIntroduction(); */
    // 返回简介html 要存在服务器上的绝对路径
    String path = "upload/choicenesscontent/" + choicenesscontent.getId() + ".html";
    String realRootPath = request.getServletContext().getRealPath("/") + path;
    File file = new File(realRootPath);
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));
    bw.write(htmlStr);
    // 拼成一个url路径
    String htmlurl =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getContextPath()
            + "/"
            + path;

    choicenesscontent.setIntroductionHtmlUrl(htmlurl);
    bw.close();
  }
コード例 #28
0
ファイル: EditFrame.java プロジェクト: BrotherPhil/ROPE
  public void save() {
    BufferedWriter sourceFile = null;

    try {
      String sourceText = sourceArea.getText();

      String cleanText = cleanupSource(sourceText);

      if (cleanText.length() != sourceText.length()) {
        sourceArea.setText(cleanText);

        String message =
            String.format(
                "One or more invalid characters at the end of the source file have been removed.");
        JOptionPane.showMessageDialog(this, message, "ROPE", JOptionPane.INFORMATION_MESSAGE);
      }

      sourceFile = new BufferedWriter(new FileWriter(sourcePath, false));
      sourceFile.write(cleanText);

      setSourceChanged(false);

      setupMenus();
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (sourceFile != null) {
        try {
          sourceFile.close();
        } catch (IOException ignore) {
        }
      }
    }
  }
コード例 #29
0
 public void rank(String modelFile, String testFile, String indriRanking) {
   Ranker ranker = rFact.loadRanker(modelFile);
   int[] features = ranker.getFeatures();
   List<RankList> test = readInput(testFile);
   if (normalize) normalize(test, features);
   try {
     BufferedWriter out =
         new BufferedWriter(new OutputStreamWriter(new FileOutputStream(indriRanking), "ASCII"));
     for (int i = 0; i < test.size(); i++) {
       RankList l = test.get(i);
       double[] scores = new double[l.size()];
       for (int j = 0; j < l.size(); j++) scores[j] = ranker.eval(l.get(j));
       int[] idx = MergeSorter.sort(scores, false);
       for (int j = 0; j < idx.length; j++) {
         int k = idx[j];
         String str =
             l.getID()
                 + " Q0 "
                 + l.get(k).getDescription().replace("#", "").trim()
                 + " "
                 + (j + 1)
                 + " "
                 + SimpleMath.round(scores[k], 5)
                 + " indri";
         out.write(str);
         out.newLine();
       }
     }
     out.close();
   } catch (Exception ex) {
     System.out.println("Error in Evaluator::rank(): " + ex.toString());
   }
 }
コード例 #30
0
  private void writeFile() throws Exception {
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;
    fos = new FileOutputStream(outFile);
    osw = new OutputStreamWriter(fos, charset);
    bw = new BufferedWriter(osw);

    for (Link link : scenario.getNetwork().getLinks().values()) {
      StringBuffer sb = new StringBuffer();
      sb.append(link.getId());

      double[] meanArray = meanCounts.get(link.getId());
      for (double mean : meanArray) {
        sb.append(separator);
        sb.append(mean);
      }
      bw.write(sb.toString());
      bw.write("\n");
    }

    bw.close();
    osw.close();
    fos.close();
  }