/* * TypeとFunctionのログを出力する。 */ private static void createLogFiles(HashSet<Type> new_types, HashSet<Function> new_funcs) { String Type_FILE_NAME = "./type.txt"; String Function_FILE_NAME = "./function.txt"; File fileL = new File(Type_FILE_NAME); File fileC = new File(Function_FILE_NAME); try { fileL.createNewFile(); fileC.createNewFile(); PrintWriter pwL = new PrintWriter(new BufferedWriter(new FileWriter(fileL))); PrintWriter pwC = new PrintWriter(new BufferedWriter(new FileWriter(fileC))); for (Type t : new_types) { // System.out.println(t.toDBString()); pwL.println(t.toDBString()); } for (Function f : new_funcs) { // System.out.println(t.toDBString()); pwC.println(f.toDBString()); } pwL.close(); pwC.close(); } catch (IOException e) { e.printStackTrace(); } }
/* write out a sh .profile file to ease testing in the terminal */ private static void writeShProfile() { File etc_profile = new File(app_opt, "etc/profile"); String global = ""; for (String s : envp) { global += "export " + s + "\n"; } File home_profile = new File(app_home, ".profile"); String local = ". " + etc_profile.getAbsolutePath() + "\n. " + new File(app_home, ".gpg-agent-info").getAbsolutePath() + "\n" + "export GPG_AGENT_INFO\n" + "export SSH_AUTH_SOCK\n"; try { FileWriter outFile = new FileWriter(etc_profile); PrintWriter out = new PrintWriter(outFile); out.println(global); out.close(); outFile = new FileWriter(home_profile); out = new PrintWriter(home_profile); out.println(local); out.close(); } catch (Exception e) { Log.e(TAG, "Cannot write file: ", e); } }
/** * 将字符串写入到文件中, * * @param filePath 文件路径+文件名 * @param fileContent 文件内容 * @param encoding 字符串编码格式 默认系统编码 * @param append 如果为true表示将fileContent中的内容添加到文件file末尾处 */ public static void writeFileByString( String filePath, String fileContent, String encoding, boolean append) { PrintWriter out = null; try { if (filePath == null || fileContent == null || fileContent.length() <= 0) { return; } if (append) { File tempFile = new File(filePath); if (!tempFile.exists()) { if (tempFile.getParentFile().mkdirs()) { if (!tempFile.createNewFile()) { return; } } } } else createNewFile(new File(filePath)); if (encoding == null || encoding.trim().length() <= 0) { out = new PrintWriter(new FileWriter(filePath)); } else { out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filePath, append), encoding)), true); } out.print(fileContent); out.close(); } catch (Exception ignored) { } finally { if (out != null) out.close(); } }
public static void main(String[] args) throws IOException, InterruptedException { for (int iter = 1; iter <= 1000; ++iter) { System.out.println("HELLO"); // ask for a value Socket s1 = new Socket("127.0.0.1", 12345); PrintWriter out = new PrintWriter(s1.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(s1.getInputStream())); out.println(-1); String response = in.readLine(); s1.close(); out.close(); in.close(); // increase by 1 int val = Integer.parseInt(response); val++; // set value Socket s2 = new Socket("127.0.0.1", 12345); out = new PrintWriter(s2.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(s2.getInputStream())); out.println(val); s2.close(); out.close(); in.close(); } }
/** Metodo que escreve os clientes num ficheiro */ public void escreveLocalidades(String fileLocalidades, String fileLigacoes, int nrlocalidades) throws FileNotFoundException, IOException { PrintWriter printloc = new PrintWriter(fileLocalidades); PrintWriter printlig = new PrintWriter(fileLigacoes); Collection<Localidade> coll = this.localidades.values(); for (Localidade l : coll) { printloc.print(l.get_Codigopostal() + "|" + l.get_Nome()); Map<String, Ligacao> ligacoes = l.get_Ligacoes(); int nrligacoes = ligacoes.size(); Collection<Ligacao> colllig = ligacoes.values(); for (Ligacao lig : colllig) { printloc.print("|1"); printlig.println( l.get_Codigopostal() + "|" + lig.get_Localidaded() + "|" + lig.get_Distancia() + "|" + lig.get_Taxas()); } printloc.print("\n"); nrlocalidades--; if (nrlocalidades == 0) break; } printloc.close(); printlig.close(); }
public String execute() throws Exception { HttpServletResponse response = null; response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); HttpSession session = ServletActionContext.getRequest().getSession(); if (session.getAttribute("id") == null) { out.print( "<script language='javascript'>alert('请重新登录!');window.location='Login.jsp';</script>"); out.flush(); out.close(); return null; } StudentBean cnbean = new StudentBean(); cnbean = new StudentDaoImpl().GetBean(Integer.parseInt(Student_ID)); cnbean.setStudent_State("迁出"); new StudentDaoImpl().Update(cnbean); OutBean outbean = new OutBean(); outbean.setOut_StudentID(Integer.parseInt(Student_ID)); outbean.setOut_Date(getNowdate()); outbean.setOut_Remark(Out_Remark); new OutDaoImpl().Add(outbean); out.print( "<script language='javascript'>alert('学生迁出操作成功!');window.location='StudentTH.jsp';</script>"); out.flush(); out.close(); return null; }
/** * The doPost method of the servlet. <br> * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String result; int userId = 0; try { userId = Integer.parseInt(request.getParameter("userId")); } catch (NumberFormatException e) { DataInfoBean info = DataInfoBean.createErrorDataInfoBean("请求数据不正确"); result = info.object2Json(); DebugUtility.p("result " + result); out.print(result); out.flush(); out.close(); return; } result = ((UserLikePhotoService) AppliationContextUtility.getBean("userLikePhotoService")) .getPhotoCount(userId); DebugUtility.p("result " + result); out.print(result); out.flush(); out.close(); }
@SubscribeEvent public void serverStopping(FEModuleServerStopEvent e) { try { votifier.shutdown(); } catch (Exception e1) { FMLLog.severe("Error closing Votifier compat thread."); FMLLog.severe(e.toString()); e1.printStackTrace(); } try { log.close(); } catch (Exception e1) { e1.printStackTrace(); } try { File file = new File(moduleDir, "offlineVoteList.txt"); if (!file.exists()) { file.createNewFile(); } PrintWriter pw = new PrintWriter(file); for (VoteEvent vote : offlineList.values()) { pw.println(vote.toString()); } pw.close(); } catch (Exception e1) { e1.printStackTrace(); } }
// 保存付汇单据的到账金额 private void saveRMBMoney(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/json"); PrintWriter out = null; try { out = response.getWriter(); // 获得将要删除附件的付汇单Id HashMap<String, String> Moneyhm = new HashMap<String, String>(); Moneyhm.put("ID", request.getParameter("ID")); Moneyhm.put("RMBMoney", request.getParameter("RMBMoney")); int iresult = GeneralManager.update(Moneyhm, "BJCustomerFuHui"); if (iresult != 1) { iresult = 0; } out.print("{\"result\":\"" + iresult + "\"}"); out.close(); } catch (Exception e) { if (out != null) { out.print("{\"result\":\"-3\"}"); out.close(); } else { e.printStackTrace(); } } finally { if (null != out) { out.flush(); out.close(); } } }
public void close(boolean store_output) throws IllegalArgumentException, IllegalStateException, IOException { if (closed) return; closed = true; started_pw.close(); all_csv_pw.close(); writeTestSuiteEnd(); writeTally(); main_serial.endTag(null, "testsuites"); main_serial.endDocument(); main_serial.flush(); out.close(); // @see PhpUnitReader#readTally { FileWriter fw = new FileWriter(new File(dir.getAbsolutePath() + "/tally.xml")); main_serial.setOutput(fw); writeTally(); // write again - this file is smaller and faster to read main_serial.flush(); fw.close(); } // // do this after finishing phpunit.xml since that's more important than alphabetizing text file // lists for (StatusListEntry e : status_list_map.values()) e.close(); if (!store_output) output_by_name = null; } // end public void close
void run() throws IOException { BufferedReader f = new BufferedReader(new FileReader("ttwo.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ttwo.out"))); StringTokenizer st; int min = 0; for (int i = 0; i < 10; i++) { st = new StringTokenizer(f.readLine()); String s = st.nextToken(); for (int j = 0; j < 10; j++) { if (s.charAt(j) == '*') { sq[i][j] = 1; } else if (s.charAt(j) == '.') { sq[i][j] = 0; } else if (s.charAt(j) == 'F') { fLoc = 10 * i + j; sq[i][j] = 0; } else { cLoc = 10 * i + j; sq[i][j] = 0; } } } while (fLoc != cLoc) { move(); min++; if (min == 160000) { out.println(0); out.close(); System.exit(0); } } out.println(min); out.close(); System.exit(0); }
private void doStuff(String rootDir, String itemRepr, String itemName) throws FileNotFoundException { String patternName = getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName; File patternFile = new File(patternName); PrintWriter writer; if (!patternFile.exists()) { writer = new PrintWriter(new FileOutputStream(patternFile)); try { writer.print(itemRepr); } finally { writer.close(); } System.out.println("Pattern not found, file " + patternName + " created."); LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile); } File graFile = new File( FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName); writer = new PrintWriter(new FileOutputStream(graFile)); try { writer.print(itemRepr); } finally { writer.close(); } LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile); FileDocumentManager.getInstance().saveAllDocuments(); }
public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(true); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); // variable int idUser = Integer.parseInt(session.getAttribute("xid").toString()); int in_codigo_mof = Integer.parseInt(request.getParameter("in_codigo_mof")); int idEstado = 0; String Rol = (String) session.getAttribute("xrol"); Rol = Rol.trim().toUpperCase(); String vc_observacion = request.getParameter("vc_observacion"); String ckaprobar = (request.getParameter("ckaprobar") != null && request.getParameter("ckaprobar").equals("1")) ? request.getParameter("ckaprobar") : "0"; Calendar Cal = Calendar.getInstance(); DataSource dataSource = getDataSource(request, "DSconnection"); orpro_ta_observaciones_mof_DAO daoMOF = new orpro_ta_observaciones_mof_DAO(dataSource); orpro_ta_observaciones_mof theForm = new orpro_ta_observaciones_mof(); idEstado = 1; // Estado Pendiente if (Rol.equals("ROL01")) { // OCDO if (ckaprobar.equals("1")) idEstado = 13; // aprobado OCO } else if (Rol.equals("ROL02")) { // USUARIO idEstado = 1; } else if (Rol.equals("ROL03")) { if (ckaprobar.equals("1")) idEstado = 15; // APROBACION ASESORIA LEGAL } // System.out.println("APROBADO POR :"+idEstado); PrintWriter writer; try { theForm.setIn_codigo_mof(in_codigo_mof); theForm.setVc_observacion(vc_observacion); writer = response.getWriter(); if (daoMOF.guardarObservacionMof(theForm, idUser, idEstado)) { writer.print("1"); } else { writer.print("0"); } writer.flush(); writer.close(); } catch (IOException ex) { writer = response.getWriter(); writer.print("0"); writer.flush(); writer.close(); Logger.getLogger(Observacion_Documentos_Gestion_Mof_Guardar.class.getName()) .log(Level.SEVERE, null, ex); } return null; // mapping.findForward(SUCCESS); }
private void crearArchivo() throws IOException, FileNotFoundException, UnsupportedEncodingException { // URL url = Thread.currentThread().getContextClassLoader().getResource("com/youpackage/"); String ruta = getServletContext().getRealPath("/js"); // System.out.println(ruta); String nombreArchivo = File.separator + "datos.js"; // System.out.println(nombreArchivo); synchronized (this) { // se sincroniza el acceso al archivo para que sea thread-safe File archivo = new File(ruta + nombreArchivo); String datosJavaScript = datosJavaAJavaScript(); if (archivo.createNewFile()) { // si el archivo no existía, se crea System.out.println("File created"); PrintWriter writer = new PrintWriter(archivo, "UTF-8"); writer.print(datosJavaScript); writer.close(); } else { // si el archivo existía y tenía una antigüedad mayor a un día, se reconstruye System.out.println("Failed to create file, it already existed"); long fechaActual = System.currentTimeMillis(); // long unDia = 1 * (24 * 60 * 60 * 1000); long diezMinutos = 10 * (60 * 1000); long vidaMaxima = diezMinutos; if (fechaActual - archivo.lastModified() > vidaMaxima) { // el archivo es "viejo", se reconstruirá if (archivo.delete()) { // se borra el archivo y se debe re-crear archivo.createNewFile(); PrintWriter writer = new PrintWriter(archivo, "UTF-8"); writer.print(datosJavaScript); writer.close(); } } } } }
public void exportMainlineDataToText() throws IOException { for (int key : detectors.keySet()) { Double[] flow = MyUtilities.scaleVector( detectors.get(key).getFlowDataArray(), (double) detectors.get(key).getNumberOfLanes()); Double[] speed = detectors.get(key).getSpeedDataArray(); Double[] density = MyUtilities.scaleVector( detectors.get(key).getDensityDataArray(), (double) detectors.get(key).getNumberOfLanes()); PrintWriter outFlow = new PrintWriter(new FileWriter(key + "_flw.txt")); PrintWriter outSpeed = new PrintWriter(new FileWriter(key + "_spd.txt")); PrintWriter outDensity = new PrintWriter(new FileWriter(key + "_dty.txt")); for (int i = 0; i < flow.length; i++) { outFlow.println(flow[i]); outSpeed.println(speed[i]); outDensity.println(density[i]); } outFlow.close(); outSpeed.close(); outDensity.close(); } }
@Test public void testAddUnstagedChanges() throws IOException, NoHeadException, NoMessageException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException, NoFilepatternException { File file = new File(db.getWorkTree(), "a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); Git git = new Git(db); git.add().addFilepattern("a.txt").call(); RevCommit commit = git.commit().setMessage("initial commit").call(); TreeWalk tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.getObjectId(0).getName()); writer = new PrintWriter(file); writer.print("content2"); writer.close(); commit = git.commit().setMessage("second commit").call(); tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("6b584e8ece562ebffc15d38808cd6b98fc3d97ea", tw.getObjectId(0).getName()); commit = git.commit().setAll(true).setMessage("third commit").setAll(true).call(); tw = TreeWalk.forPath(db, "a.txt", commit.getTree()); assertEquals("db00fd65b218578127ea51f3dffac701f12f486a", tw.getObjectId(0).getName()); }
public static void reconstruct( String input, String output, boolean isDirectory, boolean excludeCommon) { List<DEPTree> trees; PrintWriter writer; Pair<List<AbstractMention>, CoreferantSet> resolution; /* Coref Configuration */ SieveSystemCongiuration config = new SieveSystemCongiuration(TLanguage.ENGLISH); config.loadMentionDetectors(true, true, true); config.loadDefaultSieves(true, true, true, true, true, true, true, true); AbstractCoreferenceResolution coref = new SieveSystemCoreferenceResolution(config); /* ************* */ if (isDirectory) { List<String> l_filePaths = FileUtils.getFileList(input, ".cnlp", true); for (String filePath : l_filePaths) { trees = CoreferenceTestUtil.getTestDocuments(filePath, 9); resolution = coref.getEntities(trees); writer = new PrintWriter( IOUtils.createBufferedPrintStream( output + FileUtils.getBaseName(filePath) + ".reconstructed")); writer.println(reconstruct(trees, resolution.o1, resolution.o2, excludeCommon)); writer.close(); } } else { trees = CoreferenceTestUtil.getTestDocuments(input, 9); resolution = coref.getEntities(trees); writer = new PrintWriter(IOUtils.createBufferedPrintStream(output + ".reconstructed")); writer.println(reconstruct(trees, resolution.o1, resolution.o2, excludeCommon)); writer.close(); } }
// 删除付汇附件 private void deleteFuHuiAttachment(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/json"); PrintWriter out = null; try { out = response.getWriter(); // 获得将要删除附件的付汇单Id String orderId = request.getParameter("ID"); int iresult = payMoneyManager.deleteFuHuiUploadFile(orderId, 0); if (iresult != 1) { iresult = 0; } out.print("{\"result\":\"" + iresult + "\"}"); out.close(); } catch (Exception e) { if (out != null) { out.print("{\"result\":\"-3\"}"); out.close(); } else { e.printStackTrace(); } } finally { if (null != out) { out.flush(); out.close(); } } }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String captchaId = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY); String parm = (String) request.getParameter("txtResponse"); if (captchaId != null && parm != null) { if (captchaId.equals(parm)) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write( "document.getElementById('imagen_captcha').src='KaptchaServlet#" + Math.floor(Math.random() * 1100000) + "';"); out.write("document.getElementById('captcha_response').value='';"); out.write("f_grabarDatos();"); out.flush(); out.close(); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write( "document.getElementById('imagen_captcha').src='KaptchaServlet#" + Math.floor(Math.random() * 1100000) + "';"); out.write("alert('Codigo incorrecto,registra nuevamente el codigo de la imagen');"); out.write("document.getElementById('captcha_response').value='';"); out.write("document.getElementById('captcha_response').focus();"); out.write("return false;"); out.flush(); out.close(); } } }
// Main public static void main(String[] args) throws IOException { final String CSV_SEPARATOR = "\t"; EventsManager events = EventsUtils.createEventsManager(); TypeActivityAnalyzer typeActivityAnalyzer = new TypeActivityAnalyzer(300, 30 * 3600); events.addHandler(typeActivityAnalyzer); new EventsReaderXMLv1(events).parse(args[0]); typeActivityAnalyzer.finishActivities(); PrintWriter writer = new PrintWriter(new File("./data/durationsByType.txt")); for (String type : typeActivityAnalyzer.getDurations().keySet()) { for (Entry<Double, Integer> count : typeActivityAnalyzer.getDurations().get(type).entrySet()) writer.println( Time.writeTime(count.getKey()) + CSV_SEPARATOR + type + CSV_SEPARATOR + count.getValue()); } writer.close(); writer = new PrintWriter(new File("./data/performingByType.txt")); for (String type : typeActivityAnalyzer.getPeoplePerforming().keySet()) { for (Entry<Double, Integer> count : typeActivityAnalyzer.getPeoplePerforming().get(type).entrySet()) writer.println( Time.writeTime(count.getKey()) + CSV_SEPARATOR + type + CSV_SEPARATOR + count.getValue()); } writer.close(); }
public static void main(String[] args) { isMain = true; results = new double[(maxSize - minSize) + 1]; for (int i = 0; i < results.length; i++) { results[i] = 0; } String paramString = "-A DmnReflexModelAgent -d "; for (gridSize = minSize; gridSize <= maxSize; gridSize++) { for (int simNum = 0; simNum < simulations; simNum++) { VaccumAgentDriver.main((paramString + gridSize + " " + gridSize).toString().split(" ")); } } try { pw = new PrintWriter(outFileName + "X.txt"); for (int i = 0; i < results.length; i++) { pw.printf("%d\n", i + minSize); } pw.close(); pw = new PrintWriter(outFileName + "Y.txt"); for (int i = 0; i < results.length; i++) { pw.printf("%.5f\n", results[i]); } pw.close(); } catch (IOException e) { // System.out.println("Error initializing PrintWriter for output file " + outFileName); } }
private static void RetrivedBestMaches(ArrayList<String> resultingFileName, String outputTextFile) throws IOException { // TODO Auto-generated method stub PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputTextFile))); String listOfFiles = "/mnt/Projecten/transcriptorium/Tools/languagemodeling/TestSampleSelection/ListofSelectedNormalizedFiles.txt"; PrintWriter outlist = new PrintWriter(new BufferedWriter(new FileWriter(listOfFiles))); for (String st : resultingFileName) { st = st.substring(0, st.lastIndexOf(":")); // System.out.println(st); String filename = st.substring(st.lastIndexOf("/") + 1); outlist.write(filename); outlist.println(); // System.out.println(filename); BufferedReader br = new BufferedReader(new FileReader(st)); String line = br.readLine(); while (line != null) { output.append(line); output.println(); // System.out.println(line); line = br.readLine(); } br.close(); } output.flush(); output.close(); outlist.flush(); outlist.close(); System.out.println(" The file has been created in "); }
public static void generate() throws IOException { String outputPath = "/Users/Jeff/Documents"; PrintWriter out = new PrintWriter(new FileWriter(outputPath + File.separator + "formula_id.dat")); PrintWriter out_1 = new PrintWriter(new FileWriter(outputPath + File.separator + "formulaid2pageid.dat")); BufferedReader bin = new BufferedReader( new InputStreamReader( new FileInputStream(outputPath + File.separator + "formula2pageid.dat"))); String readline = ""; int i = 1; boolean ifFirst = true; while ((readline = bin.readLine()) != null) { String s[] = readline.split("\\t"); if (ifFirst) { // first is null ifFirst = false; } else { out.println(i + "_|_" + s[0]); out_1.println(i + "," + s[1]); i++; } } bin.close(); out.close(); out_1.close(); }
/** * Print network and network statistics to file. * * @param outputDir location to write files to * @param summary whether to print network statistics as well as the network itself */ public void printNetwork(String outputDir, boolean summary) { try { PrintWriter pw = new PrintWriter(outputDir + "/network.txt"); pw.print(this); pw.close(); if (summary) { pw = new PrintWriter(outputDir + "/transitivity.txt"); pw.print(getTransitivity()); pw.close(); Arrays.printToFile(getGeodesicDistances(), outputDir + "/geodesic-distances.txt"); Arrays.printToFile(getVertexInwardConnectedness(), outputDir + "/inward-connectedness.txt"); Arrays.printToFile( getVertexOutwardConnectedness(), outputDir + "/outward-connectedness.txt"); Arrays.printToFile(getVertexInDegrees(), outputDir + "/in-degree.txt"); Arrays.printToFile(getVertexOutDegrees(), outputDir + "/out-degree.txt"); } } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
/** @see org.eclipse.pde.api.tools.internal.tasks.UseTask#assertParameters() */ protected void assertParameters() throws BuildException { if (this.reportLocation == null) { StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); writer.println( NLS.bind( Messages.ApiUseTask_missing_report_location, new String[] {this.reportLocation})); writer.flush(); writer.close(); throw new BuildException(String.valueOf(out.getBuffer())); } if (this.currentBaselineLocation == null) { StringWriter out = new StringWriter(); PrintWriter writer = new PrintWriter(out); writer.println( NLS.bind( Messages.ApiUseTask_missing_baseline_argument, new String[] {this.currentBaselineLocation})); writer.flush(); writer.close(); throw new BuildException(String.valueOf(out.getBuffer())); } // stop if we don't want to see anything if (!considerapi && !considerinternal && !considerillegaluse) { throw new BuildException(Messages.UseTask_no_scan_both_types_not_searched_for); } }
private void write() { if (Constants.FORMAT_JSON.equals(action.getFormat())) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/plain"); try { PrintWriter out = response.getWriter(); out.write(getActionJSON()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } else if (Constants.FORMAT_XML.equals(action.getFormat())) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/xml"); try { PrintWriter out = response.getWriter(); out.write(getActionXML()); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
public int getCount() { int count = 0; // Load the file with the counter FileReader fileReader = null; BufferedReader bufferedReader = null; PrintWriter writer = null; try { File f = new File("FileCounter.initial"); if (!f.exists()) { f.createNewFile(); writer = new PrintWriter(new FileWriter(f)); writer.println(0); } if (writer != null) { writer.close(); } fileReader = new FileReader(f); bufferedReader = new BufferedReader(fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt(initial); } catch (Exception ex) { if (writer != null) { writer.close(); } } if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } return count; }
@Override protected Void doInBackground() throws Exception { long start = System.currentTimeMillis(); String parentFolder = this.file.getParent(); String filename = this.file.getName(); String[] infos = filename.split("\\.(?=[^\\.]+$)"); if (infos.length != 2) { System.err.println("Your file must ends with .csv extension"); throw new IOException("Your file must ends with .csv extension"); } int fileCounterLength = ("" + (this.nbTotalFiles - 1)).length(); String filenameFormat = infos[0] + "_%0" + fileCounterLength + "d." + infos[1]; int fileIndex = 0; String outputFilename = parentFolder + File.separator + String.format(filenameFormat, fileIndex); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFilename, false))); int loopIndex = 0; try (BufferedReader reader = new BufferedReader(new FileReader(this.file.getAbsolutePath()))) { int batch = 0; String line; while ((line = reader.readLine()) != null) { if ("".equals(line.trim())) { continue; } if (batch < this.batchSize) { out.println(line.trim()); batch++; } else { // System.out.println("Done: " + (batch * (fileIndex + 1))); fileIndex++; out.flush(); out.close(); outputFilename = parentFolder + File.separator + String.format(filenameFormat, fileIndex); out = new PrintWriter(new BufferedWriter(new FileWriter(outputFilename, true))); out.println(line.trim()); batch = 1; } this.publish(loopIndex++); } } finally { out.close(); } this.publish(loopIndex); System.out.println( "split finished " + (System.currentTimeMillis() - start) + " milliseconds"); return null; }
/** * closes all files * * @author [email protected] * @date Thu Dec 1 22:00:05 2011 */ void closeFiles() { try { m_wrMkdirs.close(); m_wrChmods.close(); } catch (Exception e) { System.err.println("ERROR: failed to close files: " + e.toString()); } }
// 上传付汇单据的附件 private void uploadFuHuiAttachment(HttpServletRequest request, HttpServletResponse response) { response.setContentType("text/json"); PrintWriter out = null; try { out = response.getWriter(); // 获得将要上传附件的付汇单Id String orderId = request.getParameter("ID"); int FileTypeID = Integer.parseInt(request.getParameter("FileTypeID")); // 定义将要存放文件的路径 String uploadPath = "workflow\\attachment\\payment\\"; if (FileTypeID == 1) // 说明上传的是回单,存放的目录不一样 { uploadPath = "workflow\\attachment\\paymentSD\\"; } FileUpload upload = new FileUpload(); upload.setRequest(request); upload.setUploadPath(uploadPath); String[] fileNameInfo = upload.uploadFile(); // 对上传文件的结果做分析,-1为文件格式错误,-2为文件大小超标,-3为产生异常 String uploadFileName = null; String result = null; String savedFileName = null; if (fileNameInfo == null) { result = "-1"; } else { // 上传文件成功 // 将上传信息插入数据库 uploadFileName = fileNameInfo[0]; savedFileName = fileNameInfo[1]; result = uploadFileName; int iresult = payMoneyManager.saveUploadInfoForFuHui( orderId, uploadFileName, savedFileName, FileTypeID); if (iresult != 1) { result = ""; } } out.print("{\"FileName\":\"" + result + "\",\"SaveFileName\":\"" + savedFileName + "\"}"); out.close(); } catch (Exception e) { if (out != null) { out.print("{\"result\":\"-3\"}"); out.close(); } else { e.printStackTrace(); } } finally { if (null != out) { out.flush(); out.close(); } } }