예제 #1
0
파일: RunGen.java 프로젝트: ejconlon/jerial
  public void innerExecute() throws IOException, JerializerException {
    // first arg - schema dir, second arg - dest dir
    // TODO write schemas

    File schemas = new File(schemaDir);
    assert schemas.isDirectory() && schemas.canRead();

    File dest = new File(destDir);
    assert !dest.exists();
    dest.mkdir();
    assert dest.isDirectory() && dest.canWrite();

    Set<Klass> genKlasses = new TreeSet<Klass>();

    JsonParser parser = new JsonParser();
    for (File schema : schemas.listFiles()) {
      BufferedReader reader = new BufferedReader(new FileReader(schema));
      JThing thing = parser.parse(reader);
      System.out.println(thing);
      String rootString = schemas.toURI().toString();
      if (!rootString.endsWith("/")) rootString = rootString + "/";
      String klassName =
          KlassContext.capitalize(schema.toURI().toString().substring(rootString.length()));
      String packageName = basePackage + "." + klassName.toLowerCase();

      GenWritable writable = parseSchemaThing(klassName, packageName, thing);

      Map<String, String> m = writable.makeClassToTextMap();

      final File dir = new File(destDir + "/" + klassName.toLowerCase());
      dir.mkdirs();
      for (Map.Entry<String, String> entry : m.entrySet()) {
        final String fullClass = entry.getKey();
        final String contents = entry.getValue();
        final String relName = fullClass.substring(fullClass.lastIndexOf(".") + 1) + ".java";
        final File f = new File(dir, relName);
        FileWriter writer = new FileWriter(f);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        bufferedWriter.write(contents, 0, contents.length());
        bufferedWriter.close();
      }

      genKlasses.add(new Klass(klassName, packageName));
    }

    RegistryGen registryGen =
        new RegistryGen(new Klass("GenschemaRegistryFactory", basePackage), genKlasses);
    final File g = new File(destDir + "/GenschemaRegistryFactory.java");
    for (Map.Entry<String, String> entry : registryGen.makeClassToTextMap().entrySet()) {
      final String contents = entry.getValue();
      FileWriter writer = new FileWriter(g);
      BufferedWriter bufferedWriter = new BufferedWriter(writer);
      bufferedWriter.write(contents, 0, contents.length());
      bufferedWriter.close();
      break;
    }
  }
예제 #2
0
  @Override
  synchronized void incrementNextClaimID() {
    // increment in memory
    this.nextClaimID++;

    BufferedWriter outStream = null;

    try {
      // open the file and write the new value
      File nextClaimIdFile = new File(nextClaimIdFilePath);
      nextClaimIdFile.createNewFile();
      outStream = new BufferedWriter(new FileWriter(nextClaimIdFile));

      outStream.write(String.valueOf(this.nextClaimID));
    }

    // if any problem, log it
    catch (Exception e) {
      GriefPrevention.AddLogEntry("Unexpected exception saving next claim ID: " + e.getMessage());
    }

    // close the file
    try {
      if (outStream != null) outStream.close();
    } catch (IOException exception) {
    }
  }
예제 #3
0
  /**
   * copies a file from DFS to local working directory
   *
   * @param dfsPath is the pathname to a file in DFS
   * @return the path of the new file in local scratch space
   * @throws IOException if it can't access the files
   */
  private String copyDBFile(String dfsPath) throws IOException {

    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);

    Path filenamePath = new Path(dfsPath);
    File localFile = new File(tmpDirFile, filenamePath.getName());

    if (!fs.exists(filenamePath)) {
      throw new IOException("file not found: " + dfsPath);
    }

    FSDataInputStream in = fs.open(filenamePath);
    BufferedReader d = new BufferedReader(new InputStreamReader(in));

    BufferedWriter out = new BufferedWriter(new FileWriter(localFile.getPath()));

    String line;
    line = d.readLine();

    while (line != null) {
      out.write(line + "\n");
      line = d.readLine();
    }
    in.close();
    out.close();

    return localFile.getPath();
  }
예제 #4
0
  /**
   * given a list of sequences, creates a db for use with blat
   *
   * @param seqList is the list of sequences to create the database with
   * @return the full path of the location of the database
   */
  private String dumpToFile(Map<String, String> seqList) {

    File tmpdir;
    BufferedWriter out;
    File seqFile = null;

    /*
    open temp file
     */
    try {
      seqFile = new File(tmpDirFile, "reads.fa");
      out = new BufferedWriter(new FileWriter(seqFile.getPath()));

      /*
      write out the sequences to file
      */
      for (String key : seqList.keySet()) {
        assert (seqList.get(key) != null);
        out.write(">" + key + "\n");
        out.write(seqList.get(key) + "\n");
      }

      /*
      close temp file
       */
      out.close();

    } catch (Exception e) {
      log.error(e);
      return null;
    }

    return seqFile.getPath();
  }
예제 #5
0
 public static void main(String[] args) throws IOException {
   FileReader fin = new FileReader(new File("input.txt"));
   BufferedReader input = new BufferedReader(fin);
   FileWriter fout = new FileWriter(new File("output.txt"));
   BufferedWriter out = new BufferedWriter(fout);
   StringTokenizer str = new StringTokenizer(input.readLine());
   int n = Integer.parseInt(str.nextToken());
   str = new StringTokenizer(input.readLine());
   ArrayList<Integer>[] data = new ArrayList[5000];
   for (int i = 0; i < 5000; i++) data[i] = new ArrayList<Integer>();
   for (int i = 0; i < 2 * n; i++) {
     int x = Integer.parseInt(str.nextToken());
     data[x - 1].add(i + 1);
   }
   boolean okay = true;
   for (int i = 0; i < 5000; i++) if (data[i].size() % 2 == 1) okay = false;
   if (okay) {
     for (int i = 0; i < 5000; i++) {
       for (int j = 0; j < data[i].size() / 2; j++) {
         out.write(data[i].get(2 * j) + " " + data[i].get(2 * j + 1) + "\n");
       }
     }
   } else {
     out.write("-1");
   }
   out.close();
 }
예제 #6
0
  public void ServerConnectionIncoming(String peer1, String address, String port) {
    String filename = "peer_" + peer1 + "/log_peer_" + peer1 + ".log";
    File file = new File(filename);
    if (!file.exists()) {
      CreateLog(peer1);
    }

    try {
      FileWriter fw = new FileWriter(filename, true); // the true will append the new data
      BufferedWriter bw = new BufferedWriter(fw);
      String str =
          getDate()
              + "***Server for peer: "
              + peer1
              + " is ready to listen at :"
              + address
              + " at port : "
              + port;
      bw.write(str); // appends the string to the file
      bw.newLine();
      bw.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
예제 #7
0
  public void PieceDownload(String peer1, String peer2, int index, int pieces) {
    String filename = "peer_" + peer1 + "/log_peer_" + peer1 + ".log";
    File file = new File(filename);
    if (!file.exists()) {
      CreateLog(peer1);
    }

    try {
      FileWriter fw = new FileWriter(filename, true); // the true will append the new data
      BufferedWriter bw = new BufferedWriter(fw);
      String str =
          getDate()
              + ": Peer "
              + peer1
              + " has downloaded the piece "
              + index
              + " from Peer "
              + peer2
              + ". Now the number of pieces is "
              + pieces
              + ".";
      bw.write(str); // appends the string to the file
      bw.newLine();
      bw.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
예제 #8
0
  public void Have(String peer1, String peer2, int index) {
    String filename = "peer_" + peer1 + "/log_peer_" + peer1 + ".log";
    File file = new File(filename);
    if (!file.exists()) {
      CreateLog(peer1);
    }

    try {
      FileWriter fw = new FileWriter(filename, true); // the true will append the new data
      BufferedWriter bw = new BufferedWriter(fw);
      String str =
          getDate()
              + ": Peer "
              + peer1
              + " received the 'HAVE' message from Peer "
              + peer2
              + " for the piece "
              + index
              + ".";
      bw.write(str); // appends the string to the file
      bw.newLine();
      bw.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
예제 #9
0
  // grants a group (players with a specific permission) bonus claim blocks as
  // long as they're still members of the group
  @Override
  synchronized void saveGroupBonusBlocks(String groupName, int currentValue) {
    // write changes to file to ensure they don't get lost
    BufferedWriter outStream = null;
    try {
      // open the group's file
      File groupDataFile = new File(playerDataFolderPath + File.separator + "$" + groupName);
      groupDataFile.createNewFile();
      outStream = new BufferedWriter(new FileWriter(groupDataFile));

      // first line is number of bonus blocks
      outStream.write(String.valueOf(currentValue));
      outStream.newLine();
    }

    // if any problem, log it
    catch (Exception e) {
      GriefPrevention.AddLogEntry(
          "Unexpected exception saving data for group \"" + groupName + "\": " + e.getMessage());
    }

    try {
      // close the file
      if (outStream != null) {
        outStream.close();
      }
    } catch (IOException exception) {
    }
  }
예제 #10
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);
    }
  }
예제 #11
0
  public static void main(String[] args) {
    lineNumber = 1;

    try {
      fstream = new FileWriter("output");
      bw = new BufferedWriter(fstream);
      br = new BufferedReader(new FileReader(INPUTFILENAME));
    } catch (FileNotFoundException e) {
      System.out.println(e);
    } catch (IOException e) {
      System.out.println(e);
    }

    addNodes();

    try {
      while ((line = br.readLine()) != null) {
        task = line.substring(0, line.indexOf(":"));
        input = line.substring(line.indexOf(":") + 1);
        bw.write("Output #" + Integer.toString(lineNumber) + ": ");
        if (task.equals("findDistance")) {
          findDistance(input);
        } else if (task.equals("findShortestRoute")) {
          findShortestRoute(input);
        } else if (task.equals("findNumberofRoutes")) {
          findNumberofRoutes(input);
        }
        lineNumber++;
      }

      bw.close();
    } catch (IOException e) {
      System.out.println(e);
    }
  }
예제 #12
0
 public static void outputTaskDetail(int numCtrls, int partSize, int numJobsPerPart) {
   try {
     bwTaskDetail.write(
         "JobId\tStartTime\tSubmissionTime\t" + "ExecuteTime\tFinishTime\tResultBackTime\r\n");
     for (int i = 0; i < numCtrls; i++) {
       String ctrlId = "node-" + Integer.toString(i * partSize);
       for (int j = 0; j < numJobsPerPart; j++) {
         String jobId = ctrlId + " " + Integer.toString(j);
         Job job = jobMetaData.get(jobId);
         long startTime;
         long submitTime;
         long exeTime;
         long finTime;
         long backTime;
         bwTaskDetail.write(
             jobId
                 + "\t"
                 + job.startTime
                 + "\t"
                 + job.submitTime
                 + "\t"
                 + job.exeTime
                 + "\t"
                 + job.finTime
                 + "\t"
                 + job.backTime
                 + "\r\n");
       }
     }
     bwTaskDetail.flush();
     bwTaskDetail.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #13
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();
 }
예제 #14
0
  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) {
        }
      }
    }
  }
  private static void patchConfFile(File originalConf, File dest, String library)
      throws IOException {
    Scanner sc = new Scanner(originalConf);

    try {
      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest)));

      try {
        boolean patched = false;

        while (sc.hasNextLine()) {
          String line = sc.nextLine();

          out.append(line);
          out.newLine();

          if (!patched && "[plexus.core]".equals(line)) {
            out.append("load ").append(library);
            out.newLine();

            patched = true;
          }
        }
      } finally {
        out.close();
      }
    } finally {
      sc.close();
    }
  }
  public static void decry() {
    try {
      BufferedReader bf = new BufferedReader(new FileReader("ciphertext.txt"));
      BufferedWriter wr = new BufferedWriter(new FileWriter("plaintext.txt"));
      char rkey[] = new char[26];
      for (char i = 'a'; i <= 'z'; i++) {
        if (key.charAt(i - 'a') > 'z' || key.charAt(i - 'a') < 'a') continue;
        rkey[key.charAt(i - 'a') - 'a'] = i;
      }
      System.out.println(rkey);
      StringBuffer strb;
      String str;
      while (((str = bf.readLine())) != null) {
        strb = new StringBuffer(str);
        // System.out.println(strb);
        // String ans;
        for (int i = 0; i < strb.length(); i++) {
          if (strb.charAt(i) >= 'a' && strb.charAt(i) <= 'z') {
            strb.setCharAt(i, rkey[strb.charAt(i) - 'a']);
          }
        }
        System.out.println(strb.toString());
        wr.write(strb.toString());
        wr.newLine();
      }
      // keyf.close();
      wr.close();
      bf.close();

    } catch (IOException e) {

    }
  }
예제 #17
0
  /**
   * piirtää reitin tiedostoon ja reittikartta taulukkoon
   *
   * @param käydytsolmut
   * @throws IOException
   */
  public void piirräreitti(PriorityQueue<Solmu> käydytsolmut) throws IOException {

    String nimi = new String("uk");
    BufferedWriter reittikarttatiedosto = new BufferedWriter(new FileWriter("uk"));
    Solmu solmu = new Solmu(0, 0, null, 0);

    while (!käydytsolmut.isEmpty()) {
      solmu = käydytsolmut.poll();

      for (int n = 0; n < kartankoko; n++) {
        for (int i = 0; i < kartankoko; i++) {
          if (solmu.x == n && solmu.y == i) {
            // reittikartta[i][n] = '-';
            reittikartta[i][n] = (char) (solmu.summaamatkat(0, solmu.annavanhempi()) + 65);
            // reittikarttatiedosto.write("-");
            reittikarttatiedosto.write('-');
          } else {
            reittikarttatiedosto.write(reittikartta[i][n]);
          }
        }
        reittikarttatiedosto.newLine();
      }
    }
    reittikarttatiedosto.close();
    tulostakartta(reittikartta);
  }
예제 #18
0
  /**
   * Marshalls the mgf file object to a file. If the file already exists it will be overwritten.
   *
   * @param file The file to marshall the mgf file to.
   */
  public void marshallToFile(File file) throws JMzReaderException {
    try {
      // create the object to write the file
      BufferedWriter writer = new BufferedWriter(new FileWriter(file));

      // process all additional parameters
      String parameters = marshallAdditionalParameters();

      // write the parameters
      writer.write(parameters);

      // process the pmf spectra
      for (PmfQuery q : pmfQueries) writer.write(q.toString() + "\n");

      writer.write("\n");

      // write the spectra
      for (Integer index = 0; index < 1000000; index++) {
        if (!ms2Queries.containsKey(index)) continue;

        writer.write(ms2Queries.get(index).toString() + "\n");
      }

      writer.close();

    } catch (IOException e) {
      throw new JMzReaderException("Failed to write output file", e);
    }
  }
예제 #19
0
  private String ask(String cmd) {
    BufferedWriter out = null;
    BufferedReader in = null;
    Socket sock = null;
    String ret = "";
    try {
      System.out.println(server);
      sock = new Socket(server, ServerListener.PORT);
      out = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      out.write(cmd, 0, cmd.length());
      out.flush();
      in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      int inr = in.read();
      while (inr != ';') {
        ret += Character.toString((char) inr);
        inr = in.read();
      }
    } catch (IOException io) {
      io.printStackTrace();
    } finally {
      try {
        out.close();
        in.close();
        sock.close();
      } catch (IOException io) {
        io.printStackTrace();
      }
    }

    return ret;
  }
 public static void init() throws Exception {
   Properties props = new Properties();
   int pid = OSProcess.getId();
   String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
   /** * Return file as string and then modify the string accordingly ** */
   String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
   file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
   String modified_file_str = modifyFile(file_as_str);
   FileOutputStream fos = new FileOutputStream(path);
   BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
   wr.write(modified_file_str);
   wr.flush();
   wr.close();
   props.setProperty("cache-xml-file", path);
   //    String tableName = "";
   //		  props.setProperty("mcast-port", "10339");
   try {
     //			   ds = DistributedSystem.connect(props);
     ds = (new ExceptionsDUnitTest("temp")).getSystem(props);
     cache = CacheFactory.create(ds);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new Exception("" + e);
   }
 }
예제 #21
0
  static void task1() throws FileNotFoundException, IOException, SQLException {
    // Read Input
    System.out.println("Task1 Started...");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    String task1Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(task1Input.split(":")[1].split("=")[1].split("%")[0].trim());
    if (supportPercent >= 0) {
      System.out.println("Task1 Support Percent :" + supportPercent);
      // Prepare query
      String task1Sql =
          "select  temp.iname,(temp.counttrans/temp2.uniquetrans)*100 as percent"
              + " from (select i.itemname iname,count(t.transid) counttrans from trans t, items i"
              + " where i.itemid = t.itemid group by i.itemname having count(t.transid)>=(select count(distinct transid)*"
              + supportPercent / 100
              + " from trans)"
              + ") temp , (select count(distinct transid) uniquetrans from trans) temp2 order by percent";

      PreparedStatement selTask1 = con.prepareStatement(task1Sql);
      ResultSet rsTask1 = selTask1.executeQuery();

      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.1"));
      while (rsTask1.next()) {
        bw.write("{" + rsTask1.getString(1) + "}, s=" + rsTask1.getDouble(2) + "%");
        bw.newLine();
      }
      rsTask1.close();
      bw.close();
      System.out.println("Task1 Completed...\n");
    } else System.out.println("Support percent should be a positive number");
  }
예제 #22
0
 /** @param args */
 public static void main(String[] args) {
   if (args.length > 0 && (args[0].equals("-h") || args[0].equals("-help"))) {
     System.out.println(
         "\n	\\**\n"
             + "	 * Pair Count \n"
             + "	 * True Positives  : Correctly Predicted BP\n"
             + "	 * False Positives : Incorrectly Predicted BP \n"
             + "	 * False Negatives : Base pair exists in native structure\n"
             + "	 *\n"
             + "	 * Specificity 		= FN / (TP + FP)\n"
             + "	 * Sensitivity/Recall 	= TP / (TP + FN)\n"
             + "	 * Precision 		= TP / (TP + FP)\n"
             + "	 * True Negative Rate 	= TN / (TN + FP)\n"
             + "	 * Accuracy 		= (TP + TN) / (TP + TN + FP + FN)\n"
             + "	 * F-Measure 		= 2 * Precision * Recall / (Precision + Recall)\n"
             + "	 * Matthews Correlation\n"
             + "	 * Coefficient 		= (TP * TN - FP * FN) / ((TP + FP)(TP + FN)(FP + TN)(FP + FN))\n"
             + "	 */\n\n");
   }
   if (args.length > 1)
     try {
       bf = new BufferedWriter(new FileWriter(args[1]));
     } catch (IOException e) {
       e.printStackTrace();
     }
   if (args.length > 0) {
     processFile_RNA(new File(args[0]));
   } else display("Please enter a valid \".rna\" file.");
   if (bf != null)
     try {
       bf.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
 }
  public static void toCRAWDAD(LinkTrace links, OutputStream out, double timeMul)
      throws IOException {

    StatefulReader<LinkEvent, Link> linkReader = links.getReader();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
    Map<Link, Long> activeContacts = new AdjacencyMap.Links<Long>();

    linkReader.seek(links.minTime());
    for (Link l : linkReader.referenceState()) activeContacts.put(l, links.minTime());
    while (linkReader.hasNext()) {
      for (LinkEvent lev : linkReader.next()) {
        Link l = lev.link();
        if (lev.isUp()) {
          activeContacts.put(l, linkReader.time());
        } else {
          double b = activeContacts.get(l) * timeMul;
          double e = linkReader.time() * timeMul;
          activeContacts.remove(l);
          bw.write(l.id1() + "\t" + l.id2() + "\t" + b + "\t" + e + "\n");
        }
      }
    }
    linkReader.close();
    bw.close();
  }
예제 #24
0
  /**
   * Gera uma partícula aleatória de dimensões fixas.
   *
   * <p>Define os valores para size, maxValue, dimensions, lBest e inertia.
   *
   * @param pagesArray array com as páginas do banco de dados
   * @param size quantidade de dimensões da partícula
   */
  public Particle(int[] pagesArray, int size, int inertia, Random r) throws IOException {

    maxValue = pagesArray.length;
    dimensions = new int[size];
    velocity = new int[size];
    lBest = new int[size];
    this.inertia = inertia;
    this.rnd = r;

    for (int i = 0; i < size; i++) {

      dimensions[i] = (int) (rnd.nextFloat() * pagesArray.length);
      lBest[i] = (int) (rnd.nextFloat() * pagesArray.length);
      // System.out.println("dimensions["+i+"] : "+dimensions[i]);
    }

    File f = new File("dimensions");

    FileWriter fw = new FileWriter(f, true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter pw = new PrintWriter(bw);

    pw.println("pagesArray.length " + pagesArray.length);
    for (int i = 0; i < dimensions.length; i++) {
      pw.print(dimensions[i] + " ");
    }
    pw.println();

    pw.close();
    bw.close();
    fw.close();
  }
예제 #25
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();
       }
     }
 }
예제 #26
0
 public void endWriter() {
   try {
     w.close();
   } catch (IOException e) {
     System.out.println("error closing writer");
   }
 }
예제 #27
0
  // saves changes to player data. MUST be called after you're done making
  // changes, otherwise a reload will lose them
  @Override
  public synchronized void savePlayerData(String playerName, PlayerData playerData) {
    // never save data for the "administrative" account. an empty string for
    // claim owner indicates administrative account
    if (playerName.length() == 0) return;

    BufferedWriter outStream = null;
    try {
      // open the player's file
      File playerDataFile =
          new File(playerDataFolderPath + File.separator + playerName.toLowerCase());
      playerDataFile.createNewFile();
      outStream = new BufferedWriter(new FileWriter(playerDataFile));

      // first line is last login timestamp
      if (playerData.lastLogin == null) playerData.lastLogin = new Date();
      DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
      outStream.write(dateFormat.format(playerData.lastLogin));
      outStream.newLine();

      // second line is accrued claim blocks
      outStream.write(String.valueOf(playerData.accruedClaimBlocks));
      outStream.newLine();

      // third line is bonus claim blocks
      outStream.write(String.valueOf(playerData.bonusClaimBlocks));
      outStream.newLine();

      // fourth line is a double-semicolon-delimited list of claims
      /*if (playerData.claims.size() > 0) {
      	outStream.write(this.locationToString(playerData.claims.get(0).getLesserBoundaryCorner()));
      	for (int i = 1; i < playerData.claims.size(); i++) {
      		outStream.write(";;" + this.locationToString(playerData.claims.get(i).getLesserBoundaryCorner()));
      	}
      } */

      // write out wether the player's inventory needs to be cleared on join.
      outStream.newLine();
      outStream.write(String.valueOf(playerData.ClearInventoryOnJoin));
      outStream.newLine();
    }

    // if any problem, log it
    catch (Exception e) {
      GriefPrevention.AddLogEntry(
          "GriefPrevention: Unexpected exception saving data for player \""
              + playerName
              + "\": "
              + e.getMessage());
    }

    try {
      // close the file
      if (outStream != null) {
        outStream.close();
      }
    } catch (IOException exception) {
    }
  }
 public void writeToFile(String outfilename, String script) {
   try {
     BufferedWriter out = new BufferedWriter(new FileWriter(outfilename));
     out.write(script);
     out.close();
   } catch (IOException e) {
   }
 }
  private void writeTree(GeneBranch tree, String dir) {
    try {
      BufferedWriter writer1 = new BufferedWriter(new FileWriter(dir + tree.gene + ".sif"));
      BufferedWriter writer2 = new BufferedWriter(new FileWriter(dir + tree.gene + ".format"));

      writer2.write("graph\tgrouping\ton\n");
      writer2.write("node\t" + tree.gene + "\tcolor\t255 255 200\n");

      writeBranches(tree.gene, tree, writer1, writer2);

      writer1.close();
      writer2.close();
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
  public static void main(String[] args) {

    hadoop_Training3_CATCH demo = new hadoop_Training3_CATCH();
    demo.conn = demo.initdb(demo.db_name);

    if (demo.conn == null) {
      System.out.println(" Databasse connection is null");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      try {
        br.readLine();
      } catch (Exception e) {
      }
    }

    // create new file for every run
    try {
      BufferedWriter bw = new BufferedWriter(new FileWriter(demo.logged_file_path));
      bw.close();
      bw = new BufferedWriter(new FileWriter(demo.non_logged_file_path));
      bw.close();

    } catch (IOException e1) {

      e1.printStackTrace();
    }

    try {
      BufferedReader br = new BufferedReader(new FileReader(demo.listing_file_path));
      String file_name = br.readLine();
      while (br != null) {
        System.out.println("Parsing File=" + file_name);
        int len = (file_name.split("\\\\")).length;
        demo.package_name = file_name.split("\\\\")[len - 2];
        demo.temp_file_path = file_name.replace("\\", "\\\\");
        // demo.id = 0;
        demo.ast_prser(file_name);
        file_name = br.readLine();
        // br=null;
      }
    } catch (FileNotFoundException e) {
      System.out.println("Error.. Can not open the listing file");
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }