public void testExtract() throws Exception { List<File> fileList = FolderWalker.open(FOLDER); Map<String, String> phraseMap = new TreeMap<String, String>(); int i = 0; for (File file : fileList) { System.out.print(++i + " / " + fileList.size() + " " + file.getName() + " "); String path = file.getAbsolutePath(); List<String> phraseList = MutualInformationEntropyPhraseExtractor.extract(IOUtil.readTxt(path), 3); System.out.print(phraseList); for (String phrase : phraseList) { phraseMap.put(phrase, file.getAbsolutePath()); } System.out.println(); } BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("data/phrase.txt"))); for (Map.Entry<String, String> entry : phraseMap.entrySet()) { bw.write(entry.getKey() + "\t" + entry.getValue()); bw.newLine(); } bw.close(); }
/** * Write reader to request body * <p> * The given reader will be closed once sending completes * * @param input * @return this request * @throws HttpRequestException */ public HttpRequest send(final Reader input) throws HttpRequestException { try { openOutput(); } catch (IOException e) { throw new HttpRequestException(e); } final Writer writer = new OutputStreamWriter(output, output.encoder.charset()); return new FlushOperation<HttpRequest>(writer) { @Override protected HttpRequest run() throws IOException { return copy(input, writer); } }.call(); }
/** * This method tests if Repositinioning Information works. * It creates a document using an xml file with preserveOriginalContent * and collectRepositioningInfo options keeping true and which has all * sorts of special entities like &, " etc. + it contains both * kind of unix and dos stype new line characters. It then saves the * document to the temporary location on the disk using * "save preserving document format" option and then compares the contents of * both the original and the temporary document to see if they are equal. * @throws java.lang.Exception */ public void testRepositioningInfo() throws Exception { // here we need to save the document to the file String encoding = ((DocumentImpl)doc).getEncoding(); File outputFile = File.createTempFile("test-inline1","xml"); OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outputFile),encoding); writer.write(doc.toXml(null, true)); writer.flush(); writer.close(); Reader readerForSource = new BomStrippingInputStreamReader(new URL(testFile).openStream(),encoding); Reader readerForDesti = new BomStrippingInputStreamReader(new FileInputStream(outputFile),encoding); while(true) { int input1 = readerForSource.read(); int input2 = readerForDesti.read(); if(input1 < 0 || input2 < 0) { assertTrue(input1 < 0 && input2 < 0); readerForSource.close(); readerForDesti.close(); outputFile.delete(); return; } else { assertEquals(input1,input2); } } }
/** * 多语料文件合并功能:文件夹的分词标注数据合并为一个文件 * * @throws Exception */ public void dumpCorpusFolderToFile() throws Exception { final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(CORPUS_FILE_PATH))); CorpusLoader.walk(CORPUS_FOLDER_PATH, document -> { List<List<Word>> simpleSentenceList = document.getSimpleSentenceList(); for (List<Word> wordList : simpleSentenceList) { try { for (Word word : wordList) { bw.write(word.toString()); bw.write(' '); } bw.newLine(); } catch (IOException e) { e.printStackTrace(); } } }); bw.close(); }
public void save(OutputStream outStream) throws IOException { BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8")); String aKey; Object aValue; for (Enumeration e = keys(); e.hasMoreElements();) { aKey = (String) e.nextElement(); aValue = get(aKey); out.write(aKey + " = " + aValue); out.newLine(); } out.flush(); out.close(); }
@Override protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Charset charset = getCharset(outputMessage.getHeaders()); try (OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset)) { if (ignoreType) { gsonForWriter.toJson(o, writer); return; } if (type != null) { gsonForWriter.toJson(o, type, writer); return; } gsonForWriter.toJson(o, writer); } catch (JsonIOException ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } }
@Override public RequestBody convert(T value) throws IOException { //if (String.class.getName().equals(value.getClass().getName())) { // return RequestBody.create(MediaType.parse("text/plain"), value.toString()); //} Buffer buffer = new Buffer(); Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8); JsonWriter jsonWriter = gson.newJsonWriter(writer); try { adapter.write(jsonWriter, value); jsonWriter.flush(); } catch (IOException e) { throw new AssertionError(e); // Writing to Buffer does no I/O. } finally { jsonWriter.close(); } return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); }
public static void writetxt(String txtPath, String txtCont) { try { File f = new File(txtPath); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f,true), "UTF-8"); BufferedWriter writer = new BufferedWriter(write); writer.write(txtCont); writer.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Posts string data (i.e. JSON string) to the specified URL * connection. * * @param con The URL connection. Must be in HTTP POST mode. Must not * be {@code null}. * @param data The string data to post. Must not be {@code null}. * * @throws JSONRPC2SessionException If an I/O exception is encountered. */ private static void postString(final URLConnection con, final String data) throws JSONRPC2SessionException { try { OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); wr.write(data); wr.flush(); wr.close(); } catch (IOException e) { throw new JSONRPC2SessionException( "Network exception: " + e.getMessage(), JSONRPC2SessionException.NETWORK_EXCEPTION, e); } }
void copyFile(Path src, Path target) throws Exception { try (InputStream in = Files.newInputStream(src); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); OutputStream out = new BufferedOutputStream( Files.newOutputStream(target, CREATE, APPEND)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out))) { String line = null; while ((line = reader.readLine()) != null) { bw.write(line); } } catch (IOException x) { throw new Exception(x.getMessage()); } }
@Override protected void handleStatusOk(final HttpServletRequest req, final HttpServletResponse resp, String escapdPathInfo) throws ServletException { try { final String body = catalogSupplier.get(); try (final OutputStream os = resp.getOutputStream(); final OutputStreamWriter osw = new OutputStreamWriter(os)) { osw.write(body); osw.flush(); } } catch (final Exception e) { final String msg = "Error while assembling test catalog for all tests."; LOGGER.error(msg, e); throw new ServletException(msg, e); } }
static public byte[] calulateHash(JsonElement contents) { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new InternalError("MD5 MessageDigest is not available"); } OutputStream byteSink = new OutputStream() { @Override public void write(int b) throws IOException { // ignore, since this is only used to calculate MD5 } }; DigestOutputStream dis = new DigestOutputStream(byteSink, md); new Gson().toJson(contents, new OutputStreamWriter(dis, Charset.forName(DEFAULT_CHARSET_NAME))); return dis.getMessageDigest().digest(); }
/** * Writes the user's password to a tmp file with 0600 permissions. * @return the filename used. */ public static String writePasswordFile(Configuration conf) throws IOException { // Create the temp file to hold the user's password. String tmpDir = conf.get( ConfigurationConstants.PROP_JOB_LOCAL_DIRECTORY, "/tmp/"); File tempFile = File.createTempFile("mysql-cnf", ".cnf", new File(tmpDir)); // Make the password file only private readable. DirectImportUtils.setFilePermissions(tempFile, "0600"); // If we're here, the password file is believed to be ours alone. The // inability to set chmod 0600 inside Java is troublesome. We have to // trust that the external 'chmod' program in the path does the right // thing, and returns the correct exit status. But given our inability to // re-read the permissions associated with a file, we'll have to make do // with this. String password = DBConfiguration.getPassword((JobConf) conf); BufferedWriter w = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(tempFile))); w.write("[client]\n"); w.write("password=" + password + "\n"); w.close(); return tempFile.toString(); }
public T httpsPost(String jsonBody, Class<T> clazz) throws IOException { URL url = new URL(HTTPS_PROTOCOL, ACCOUNT_KEY_SERVICE_HOST, HTTPS_PORT, ACCOUNT_KEY_ENDPOINT); httpsConnection = (HttpsURLConnection) url.openConnection(); httpsConnection.setRequestMethod(HttpRequestMethod.POST.toString()); setConnectionParameters(httpsConnection, HttpRequestMethod.POST); httpsConnection.setFixedLengthStreamingMode(jsonBody.getBytes().length); try (OutputStreamWriter out = new OutputStreamWriter( httpsConnection.getOutputStream())) { out.write(jsonBody); } StringBuilder sb = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader( httpsConnection.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } } // setFieldNamingPolicy is used to here to convert from // lower_case_with_underscore names retrieved from end point to camel // case to match POJO class Gson gson = new GsonBuilder().setFieldNamingPolicy( FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); return gson.fromJson(sb.toString(), clazz); }
private static FileObject createTestFile (FileObject root, String path, String fileName, String content) throws IOException { FileObject pkg = path != null ? FileUtil.createFolder(root, path) : root; assertNotNull (pkg); FileObject data = pkg.createData(fileName); FileLock lock = data.lock(); try { PrintWriter out = new PrintWriter (new OutputStreamWriter (data.getOutputStream(lock))); try { out.println (content); } finally { out.close(); } } finally { lock.releaseLock(); } return data; }
public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(8888); System.out.println("opening the Server...."); Socket s = ss.accept(); System.out.println("Client:"+s.getInetAddress().getLocalHost()+"have connected to the Server"); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //read the message from the client String UserName = br.readLine(); String PassWord = br.readLine(); System.out.println("Name:"+UserName); System.out.println("PassWord:"+PassWord); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write("OK\n"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } }
@Override public FileObject createFromTemplate(FileObject template, FileObject targetFolder, String name, Map<String, Object> parameters) throws IOException { String nameUniq = FileUtil.findFreeFileName(targetFolder, name, template.getExt()); FileObject newFile = FileUtil.createData(targetFolder, nameUniq + '.' + template.getExt()); Charset templateEnc = FileEncodingQuery.getEncoding(template); Charset newFileEnc = FileEncodingQuery.getEncoding(newFile); InputStream is = template.getInputStream(); Reader reader = new BufferedReader(new InputStreamReader(is, templateEnc)); OutputStream os = newFile.getOutputStream(); Writer writer = new BufferedWriter(new OutputStreamWriter(os, newFileEnc)); int cInt; while ((cInt = reader.read()) != -1) { writer.write(cInt); } writer.close(); reader.close(); return newFile; }
public Cfg() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(os); w.write("handlers=java.util.logging.FileHandler\n"); w.write(".level=100\n"); w.write("java.util.logging.FileHandler.pattern=" + log.toString().replace('\\', '/') +"\n"); w.close(); LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray())); }
public void sendContent(FacesContext context, OutputStream out) throws IOException { Writer outw = new OutputStreamWriter(out, "UTF-8"); UIXTable table = getTable(); Object rowKey = table.getRowKey(); for (int i = 0; i < table.getRowCount(); i++) { table.setRowIndex(i); if (!table.isRowAvailable()) break; _exportRow(table, outw); } outw.flush(); table.setRowKey(rowKey); }
public void update() throws IOException { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out))/*Files.newBufferedWriter(outputPath)*/) { writeHeader(writer); for (Iterator<ClassNode> it = application.iterator(); it.hasNext();) { final ClassNode clazz = it.next(); if (hooks.isEmpty()) break; for (MethodNode method : clazz.methods) { for (Iterator<Hook> hit = hooks.iterator(); hit.hasNext();) { Hook hook = hit.next(); if (hook.match(clazz, method, writer)) hit.remove(); } } } writeFooter(writer); } if (!hooks.isEmpty()) { System.err.println(hooks); throw new RuntimeException("Unconsumed hooks"); } }
@Test public void test48() throws Exception { byte[] buffer; String test = "M�nchen"; ByteArrayOutputStream stream = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, Charset.forName("UTF-8"))); writer.write(test); writer.close(); buffer = stream.toByteArray(); stream.close(); CsvReader reader = new CsvReader(new InputStreamReader( new ByteArrayInputStream(buffer), Charset.forName("UTF-8"))); Assert.assertTrue(reader.readRecord()); Assert.assertEquals(test, reader.get(0)); reader.close(); }
@ApiMethod public static void write(File file, String text) throws Exception { if (!file.exists()) file.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); bw.write(text); bw.flush(); bw.close(); }
/** * Utility method to create a writer when passed an OutputStream. Make * sure to wrap an <code>OutputStreamWriter</code> using an * <code>XMLWriter</code> for performance reasons. * * @param os Underlying OutputStream * @param encoding Encoding used to convert chars into bytes */ private void setOutputUsingStream(OutputStream os, String encoding) throws IOException { fOutputStream = os; if (encoding != null) { if (encoding.equalsIgnoreCase("utf-8")) { fWriter = new UTF8OutputStreamWriter(os); } else { fWriter = new XMLWriter(new OutputStreamWriter(os, encoding)); fEncoder = Charset.forName(encoding).newEncoder(); } } else { encoding = SecuritySupport.getSystemProperty("file.encoding"); if (encoding != null && encoding.equalsIgnoreCase("utf-8")) { fWriter = new UTF8OutputStreamWriter(os); } else { fWriter = new XMLWriter(new OutputStreamWriter(os)); } } }
@Override public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String,Object> httpHeaders, OutputStream entityStream) throws IOException { Writer out = new OutputStreamWriter(entityStream, StandardCharsets.UTF_8); if (Iterable.class.isAssignableFrom(type)) { for (Object row : (Iterable<?>) o) { out.append(toCSV(row)).append('\n'); } } else { out.append(toCSV(o)).append('\n'); } out.flush(); }
/** * write lines. * * @param os output stream. * @param lines lines. * @throws IOException */ public static void writeLines(OutputStream os, String[] lines) throws IOException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(os)); try { for( String line : lines ) writer.println(line); writer.flush(); } finally { writer.close(); } }
private Supplier<FileObject> writeFile( @NonNull final FileObject folder, @NonNull final String name, @NonNull final Supplier<String> content) { return () -> { try { final FileObject file = FileUtil.createData(folder, name); try (PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(), "UTF-8"))) { //NOI18N out.println(content.get()); } return file; } catch (IOException ioe) { throw new RuntimeException(ioe); } }; }
public SU(boolean root, String tag) { mRoot = root; mTag = tag; try { if (mTag != null) { Log.i(mTag, String.format("%s initialized", root ? "SU" : "SH")); } firstTry = true; mProcess = Runtime.getRuntime().exec(root ? "su" : "sh"); mWriter = new BufferedWriter(new OutputStreamWriter(mProcess.getOutputStream())); mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream())); } catch (IOException e) { if (mTag != null) { Log.e(mTag, root ? "Failed to run shell as su" : "Failed to run shell as sh"); } denied = true; closed = true; } }
public void onClick(View v){ try{ File myFile = new File(v.getContext().getExternalFilesDir(null), "myFile.txt"); myFile.createNewFile(); FileOutputStream fOut = new FileOutputStream(myFile); OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut); myOutWriter.append(this.TextArea.getText()); myOutWriter.close(); fOut.close(); } catch (Exception e){ e.printStackTrace(); } }
private void responseClient(Socket client) throws IOException { //用于接收客户端消息 BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); //用于向客户端发送消息 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true); out.println("欢迎来到聊天室!"); while (!mIsServiceDestroyed) { String str = in.readLine(); System.out.println("msg from client: " + str); if (str == null) { break; } int i = new Random().nextInt(mDefinedMessages.length); String msg = mDefinedMessages[i]; out.println(msg); System.out.println("send: " + msg); } System.out.println("client quit."); //关闭流 MyUtil.close(out); MyUtil.close(in); client.close(); }
public ResponseWriter( final OutputStream outStream, final String lineSeparator, final String encoding) throws UnsupportedEncodingException { super(new BufferedWriter(new OutputStreamWriter(outStream, encoding))); this.outStream = outStream; this.encoding = encoding; }
/** * Construct a new ResponseWriter, wrapping the specified writer and * attached to the specified response. * * @param writer OutputStreamWriter to which we are attached * @param stream ResponseStream to which we are attached */ public ResponseWriter(OutputStreamWriter writer, ResponseStream stream) { super(writer); this.stream = stream; this.stream.setCommit(false); }
/** * 把内容写入文件 * * @param filePath * @param fileContent */ public static void write(String filePath, String fileContent) { try { FileOutputStream fo = new FileOutputStream(filePath); OutputStreamWriter out = new OutputStreamWriter(fo, "UTF-8"); out.write(fileContent); out.close(); } catch (IOException ex) { System.err.println("Create File Error!"); ex.printStackTrace(); } }
/** * Creates a {@link CSVPrinter} instance * * @param delimiter The delimiter * @param outputStream The outputStream where the csv will be printed to * @return The CSVPrinter * @throws IOException if any IO error occurs */ CSVPrinter createInstance(char delimiter, OutputStream outputStream) throws IOException { final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream); return new CSVPrinter(outputStreamWriter, CSVFormat .DEFAULT .withDelimiter(delimiter) .withTrim() ); }
public void write(char[] cbuf, int off, int len) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter writer = m_encoding == null ? new OutputStreamWriter(baos) : new OutputStreamWriter(baos, m_charset); writer.write(cbuf, off, len); writer.close(); m_randomAccessFile.write(baos.toByteArray()); }
/** * SSL/TLS negotiation. Acquires an SSL socket of a control * connection and carries out handshake processing. * @throws java.io.IOException If server negotiation fails */ protected void sslNegotiation() throws IOException { plainSocket = _socket_; initSslContext(); SSLSocketFactory ssf = context.getSocketFactory(); String ip = _socket_.getInetAddress().getHostAddress(); int port = _socket_.getPort(); SSLSocket socket = (SSLSocket) ssf.createSocket(_socket_, ip, port, false); socket.setEnableSessionCreation(isCreation); socket.setUseClientMode(isClientMode); // server mode if (!isClientMode) { socket.setNeedClientAuth(isNeedClientAuth); socket.setWantClientAuth(isWantClientAuth); } if (protocols != null) { socket.setEnabledProtocols(protocols); } if (suites != null) { socket.setEnabledCipherSuites(suites); } socket.startHandshake(); _socket_ = socket; _controlInput_ = new BufferedReader(new InputStreamReader( socket .getInputStream(), getControlEncoding())); _controlOutput_ = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream(), getControlEncoding())); }
public static void updateConjs(Connection con) throws SQLException, IOException { MyDictionary dictionary = new MyDictionary(); Statement stmt = con.createStatement(); long k = 0; ResultSet rs = stmt.executeQuery("SELECT \n" + " lexem.formUtf8General as lemma,\n" + " definition.internalRep as definition\n" + "from lexem \n" + "JOIN lexemdefinitionmap on lexemdefinitionmap.lexemId=lexem.Id \n" + "JOIN definition on definition.id = lexemdefinitionmap.definitionId \n" + "where definition.internalRep LIKE '%#conj.%' \n" + "ORDER BY lexem.formUtf8General"); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(MyDictionary.folder + "grabedForUse/" + conjsFile), "UTF8")); while (rs.next()) { MyDictionaryEntry entry = new MyDictionaryEntry(rs.getString("lemma"), null, null, null); entry.setLemma(rs.getString("lemma")); entry.setMsd("Cs"); preprocessEntry(entry, 84); if (!dictionary.contains(entry)) { out.write(entry.toString() + "\n"); dictionary.Add(entry); k++; } } stmt.close(); rs.close(); out.close(); System.out.println("Finished conjunctions (" + k + " added)"); }
public StatusQuery(String ip, int port) { this.hostname = ip; this.port = port; try { socket = new Socket(ip, port); bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch (IOException e) { e.printStackTrace(); } }
/** * Open the new log file for the date specified by <code>dateStamp</code>. */ protected synchronized void open() { // Open the current log file // If no rotate - no need for dateStamp in fileName File pathname = getLogFile(rotatable && !renameOnRotate); Charset charset = null; if (encoding != null) { try { charset = B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); } } if (charset == null) { charset = Charset.defaultCharset(); } try { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( new FileOutputStream(pathname, true), charset), 128000), false); currentLogFile = pathname; } catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); } }
/** * Method write. * * @param actions * @param writer * @param document * @throws java.io.IOException */ public void write(ActionToGoalMapping actions, Document document, OutputStreamWriter writer) throws java.io.IOException { Format format = Format.getRawFormat() .setEncoding(writer.getEncoding()) .setLineSeparator(System.getProperty("line.separator")); write(actions, document, writer, format); }
public static String encodeCanonical(JsonObject obj) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonWriterUnchecked writer = new JsonWriterUnchecked(new OutputStreamWriter(out, StandardCharsets.UTF_8)); writer.setIndent(""); writer.setHtmlSafe(false); writer.setLenient(false); encodeCanonical(obj, writer); writer.close(); return out.toString(StandardCharsets.UTF_8.name()); } catch (IOException e) { throw new JsonCanonicalException(e); } }