Java Examples for java.io.OutputStreamWriter
The following java examples will help you to understand the usage of java.io.OutputStreamWriter. These source code samples are taken from different open source projects.
Example 1
| Project: elasticsearch-oai-master File: Runner.java View source code |
public static void main(String[] args) {
try {
Class clazz = Class.forName(args[0]);
CommandLineInterpreter commandLineInterpreter = (CommandLineInterpreter) clazz.newInstance();
commandLineInterpreter.reader(new InputStreamReader(System.in, "UTF-8")).writer(new OutputStreamWriter(System.out, "UTF-8")).run();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}Example 2
| Project: javardices-master File: TalExecute.java View source code |
public static void main(String[] args) {
try {
if ((args.length < 1) || StringUtils.isBlank(args[0])) {
throw new IllegalArgumentException("missing template file");
}
String curDir = System.getProperty("user.dir");
String template = args[0];
String templatePath = String.format("file://%s/templates/input/%s", curDir, template);
JptInstance jpt = JptInstanceBuilder.getJptInstance(URI.create(templatePath));
Writer out = new OutputStreamWriter(System.out);
jpt.render(out);
out.flush();
} catch (Throwable t) {
Shutdown.now(t);
}
}Example 3
| Project: li-old-master File: Demo.java View source code |
public static void main(String[] args) {
Engine engine = Engine.getIntense(Convert.toMap("TEMPLATE_DIRECTORY", "D:/workspace/li/dev/li/template/demo/"));
Template template = engine.getTemplate("index.htm");
Map<Object, Object> params = new HashMap<Object, Object>();
params.put("name", "limingwei");
params.put("flag", true);
template.render(params, new OutputStreamWriter(System.out));
}Example 4
| Project: mock-httpserver-master File: CharOutStreamTest.java View source code |
@Test
public void testCharOutStreamBehaviour() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter charOut = new OutputStreamWriter(out, Charsets.UTF_8);
charOut.write("Test");
charOut.flush();
out.write("Test2".getBytes(Charsets.UTF_8));
charOut.write("Test3");
charOut.close();
out.close();
String s = out.toString(Charsets.UTF_8.name());
assertEquals("TestTest2Test3", s);
}Example 5
| Project: plato-master File: CharacterisationReportGeneratorTest.java View source code |
@Test
public void testSimpleFITSReport() throws Exception {
Reader simpleFits = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("fits/simple-fits.xml"), "UTF8");
Reader fitsToHtml = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("fits/fits-to-html.xsl"), "UTF8");
StringBuilder buffer = new StringBuilder();
CharacterisationReportGenerator reportGen = new CharacterisationReportGenerator();
reportGen.generateReportFromXML(simpleFits, fitsToHtml, new OutputStreamWriter(System.out));
}Example 6
| Project: tropo-webapi-java-master File: IOUtils.java View source code |
public static String read(Reader input) {
try {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
OutputStreamWriter output = new OutputStreamWriter(byteArray);
char[] buffer = new char[1024 * 4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
output.flush();
return new String(byteArray.toByteArray());
} catch (Exception e) {
throw new TropoException("Error reading from Reader", e);
}
}Example 7
| Project: 101simplejava-master File: Unparsing.java View source code |
public static void copy(String in, String out) throws IOException {
Recognizer recognizer = recognizeCompany(in);
Writer writer = new OutputStreamWriter(new FileOutputStream(out));
String lexeme = null;
Token current = null;
while (recognizer.hasNext()) {
current = recognizer.next();
lexeme = recognizer.getLexeme();
// noop
// write
writer.write(lexeme);
}
writer.close();
}Example 8
| Project: ActivityForceNewTask-master File: Logger.java View source code |
private void addLogItem(Context context, String logItem) {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(context.openFileOutput(Common.LOG_FILE, Context.MODE_APPEND)));
writer.write(logItem + eol);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 9
| Project: audit-master File: MainActivity.java View source code |
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
OutputStreamWriter os = null;
FileOutputStream fos = null;
String FILEPATH = "/storage/sdcard1/test/";
fos = new FileOutputStream(FILEPATH + "OutputStreamWrite");
os = new OutputStreamWriter(fos, "UTF-8");
new BufferedWriter(os);
os.write("writeByOutputStreamWrite\n");
os.close();
fos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}Example 10
| Project: available-master File: TestFactoryClient.java View source code |
@Ignore
@Test
public void testSendMsg() throws UnknownHostException, IOException, InterruptedException {
Socket socket = new Socket("127.0.0.1", 5551);
OutputStream os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
// dos.write("hello".length());
for (int i = 0; i < 10; i++) {
dos.writeInt("hah".length());
dos.write("hah".getBytes());
}
// writer.write("hello".getBytes());
// OutputStreamWriter writer = new OutputStreamWriter(dos);
// writer.flush();
TimeUnit.SECONDS.sleep(50);
}Example 11
| Project: blaze-utils-master File: HttpPostInvokerJob.java View source code |
@Override
protected URLConnection createConnection(String url, String parameterString) throws IOException {
OutputStreamWriter wr = null;
try {
URLConnection con = new URL(url).openConnection();
con.setDoOutput(true);
wr = new OutputStreamWriter(con.getOutputStream());
wr.write(parameterString);
wr.flush();
return con;
} finally {
if (wr != null) {
try {
wr.close();
} catch (IOException ex) {
}
}
}
}Example 12
| Project: common-java-cookbook-master File: JoinReaders.java View source code |
public static void main(String[] args) throws Exception {
Charset utf8 = Charset.forName("UTF-8");
InputSupplier<InputStreamReader> rs1 = Files.newReaderSupplier(new File("data", "test1.txt"), utf8);
InputSupplier<InputStreamReader> rs2 = Files.newReaderSupplier(new File("data", "test2.txt"), utf8);
InputSupplier<Reader> combined = CharStreams.join(rs1, rs2);
OutputSupplier<OutputStreamWriter> ws = Files.newWriterSupplier(new File("output.txt"), utf8, false);
CharStreams.copy(combined, ws);
}Example 13
| Project: ctSESAM-android-master File: UTF8.java View source code |
public static byte[] encode(CharSequence input) {
SecureByteArrayOutputStream stream = new SecureByteArrayOutputStream();
if (!Charset.isSupported("UTF-8")) {
System.out.println("UTF-8 is not supported.");
}
OutputStreamWriter writer = new OutputStreamWriter(stream, Charset.forName("UTF-8"));
try {
for (int i = 0; i < input.length(); i++) {
writer.write(input.charAt(i));
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
byte[] output = stream.toByteArray();
stream.emptyBuffer();
return output;
}Example 14
| Project: dex2jar-master File: SmaliTest.java View source code |
@Test
public void test() throws IOException {
DexFileNode dfn = new DexFileNode();
new Smali().smaliFile(new File("src/test/resources/a.smali").toPath(), dfn);
for (DexClassNode dcn : dfn.clzs) {
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
new BaksmaliDumper(true, true).baksmaliClass(dcn, new BaksmaliDumpOut(w));
w.flush();
}
}Example 15
| Project: EMB-master File: DummyMain.java View source code |
public static void main(String[] args) throws Exception {
System.out.println(Arrays.asList(args));
File thisFolder = new File(SelfrunTest.class.getResource("/org/embulk/cli/DummyMain.class").toURI()).getParentFile();
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(thisFolder, "args.txt")), Charset.defaultCharset()))) {
for (String arg : args) {
writer.write(arg);
writer.newLine();
}
}
}Example 16
| Project: embulk-master File: DummyMain.java View source code |
public static void main(String[] args) throws Exception {
System.out.println(Arrays.asList(args));
File thisFolder = new File(SelfrunTest.class.getResource("/org/embulk/cli/DummyMain.class").toURI()).getParentFile();
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(thisFolder, "args.txt")), Charset.defaultCharset()))) {
for (String arg : args) {
writer.write(arg);
writer.newLine();
}
}
}Example 17
| Project: FireflowEngine20-master File: SocketLineHandler.java View source code |
public void handle(Socket socket) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer bw = new OutputStreamWriter(socket.getOutputStream());
String line;
while ((line = br.readLine()) != null) {
String re = handleLine(line);
if (!Strings.isBlank(re)) {
bw.write(re);
bw.flush();
}
}
}Example 18
| Project: fudannlp-master File: CharEnc.java View source code |
public static void processLabeledData(String input, String enc1, String enc2) throws Exception {
FileInputStream is = new FileInputStream(input);
// is.skip(3); //skip BOM
BufferedReader r = new BufferedReader(new InputStreamReader(is, enc1));
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(input + "." + enc2), enc2);
while (true) {
String sent = r.readLine();
if (null == sent)
break;
w.write(sent);
w.write('\n');
}
r.close();
w.close();
}Example 19
| Project: javaccng-master File: TransformerTest.java View source code |
@Test
public void test() throws IOException, ParseException {
String source = Resources.toString(Resources.getResource("divide.toy"), Charsets.UTF_8);
ToyParser parser = new ToyParser(new ToyScanner(new CharStream.Escaping(new CharStream.ForCharSequence(source))));
ASTCompilationUnit cu = parser.CompilationUnit();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
try {
cu.process(out);
} finally {
out.close();
}
}Example 20
| Project: liquibase-master File: ChangeLogSyncTask.java View source code |
@Override
public void executeWithLiquibaseClassloader() throws BuildException {
Liquibase liquibase = getLiquibase();
OutputStreamWriter writer = null;
try {
FileResource outputFile = getOutputFile();
if (outputFile != null) {
writer = new OutputStreamWriter(outputFile.getOutputStream(), getOutputEncoding());
liquibase.changeLogSync(new Contexts(getContexts()), getLabels(), writer);
} else {
liquibase.changeLogSync(new Contexts(getContexts()), getLabels());
}
} catch (UnsupportedEncodingException e) {
throw new BuildException("Unable to generate sync SQL. Encoding [" + getOutputEncoding() + "] is not supported.", e);
} catch (IOException e) {
throw new BuildException("Unable to generate sync SQL. Error creating output writer.", e);
} catch (LiquibaseException e) {
throw new BuildException("Unable to sync change log. " + e.toString(), e);
} finally {
FileUtils.close(writer);
}
}Example 21
| Project: Mint-Programming-Language-master File: Flourish.java View source code |
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
try {
final PrintStream saved = System.out;
OutputStreamWriter outputStream = new OutputStreamWriter(System.out, "UTF-8");
outputStream.write(args.get(0).value);
outputStream.close();
System.setOut(saved);
} catch (Throwable tossed) {
System.out.println(tossed);
Mint.printStackTrace(tossed.getStackTrace());
}
return Constants.MINT_TRUE;
}Example 22
| Project: MintChime-Editor-master File: Flourish.java View source code |
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
try {
final PrintStream saved = System.out;
OutputStreamWriter outputStream = new OutputStreamWriter(System.out, "UTF-8");
outputStream.write(args.get(0).value);
outputStream.close();
System.setOut(saved);
} catch (Throwable tossed) {
System.out.println(tossed);
Mint.printStackTrace(tossed.getStackTrace());
}
return Constants.MINT_TRUE;
}Example 23
| Project: nutz-master File: SocketLineHandler.java View source code |
public void handle(Socket socket) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Writer bw = new OutputStreamWriter(socket.getOutputStream());
String line;
while ((line = br.readLine()) != null) {
String re = handleLine(line);
if (!Strings.isBlank(re)) {
bw.write(re);
bw.flush();
}
}
}Example 24
| Project: ocular-master File: FileHelper.java View source code |
public static void writeString(String path, String str) {
BufferedWriter out = null;
try {
File f = new File(path);
f.getAbsoluteFile().getParentFile().mkdirs();
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8"));
out.write(str);
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
if (out != null) {
try {
out.close();
} catch (Exception ex) {
}
}
}
}Example 25
| Project: opentestbed-master File: GameTester.java View source code |
public static void main(String[] args) {
Deck deck = new RandomDeck();
PublicGameInfo gameInfo = new PublicGameInfo();
gameInfo.setNumSeats(5);
gameInfo.setPlayer(0, PublicPlayerInfo.create("player1", 200, new AlwaysCallBot()));
gameInfo.setPlayer(2, PublicPlayerInfo.create("player2", 200, new AlwaysCallBot()));
gameInfo.setPlayer(4, PublicPlayerInfo.create("player3", 200, new AlwaysCallBot()));
gameInfo.setBlinds(1, 2);
HandHistoryWriter hhWriter = new HandHistoryWriter();
hhWriter.setWriter(new OutputStreamWriter(System.out));
gameInfo.addGameObserver(hhWriter);
Dealer dealer = new Dealer(deck, gameInfo);
dealer.playHand();
dealer.playHand();
}Example 26
| Project: pgjdbc-master File: PSQLWarningTest.java View source code |
@Test
public void testPSQLLogsToDriverManagerMessage() throws Exception {
Connection con = TestUtil.openDB();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DriverManager.setLogWriter(new PrintWriter(new OutputStreamWriter(baos, "ASCII")));
Statement stmt = con.createStatement();
stmt.execute("DO language plpgsql $$ BEGIN RAISE NOTICE 'test notice'; END $$;");
assertTrue(baos.toString().contains("NOTICE: test notice"));
stmt.close();
con.close();
}Example 27
| Project: pitest-master File: FileWriterFactory.java View source code |
@Override
public PrintWriter create() {
this.file.getParentFile().mkdirs();
try {
if (this.writer == null) {
this.writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(this.file), "UTF-8"));
}
return this.writer;
} catch (final IOException e) {
throw Unchecked.translateCheckedException(e);
}
}Example 28
| Project: PokerbotServer-master File: GameTester.java View source code |
public static void main(String[] args) {
Deck deck = new RandomDeck();
PublicGameInfo gameInfo = new PublicGameInfo();
gameInfo.setNumSeats(5);
gameInfo.setPlayer(0, PublicPlayerInfo.create("player1", 200, new AlwaysCallBot()));
gameInfo.setPlayer(2, PublicPlayerInfo.create("player2", 200, new AlwaysCallBot()));
gameInfo.setPlayer(4, PublicPlayerInfo.create("player3", 200, new AlwaysCallBot()));
gameInfo.setBlinds(1, 2);
HandHistoryWriter hhWriter = new HandHistoryWriter();
hhWriter.setWriter(new OutputStreamWriter(System.out));
gameInfo.addGameObserver(hhWriter);
Dealer dealer = new Dealer(deck, gameInfo);
dealer.playHand();
dealer.playHand();
}Example 29
| Project: sitemesh2-master File: OutputServlet.java View source code |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mode = request.getParameter("out");
PrintWriter pw = null;
if (mode.equals("stream")) {
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
pw = new PrintWriter(osw);
}
if (pw == null) {
pw = response.getWriter();
}
response.setContentType("text/html");
pw.println("<html><head><title>Servlet using " + mode + "</title></head>");
pw.println("<body>This is a servlet using " + mode + " to output</body></html>");
pw.flush();
}Example 30
| Project: softwaremill-common-master File: MasterPasswordSetterClient.java View source code |
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", MasterPasswordSetterServer.PORT);
System.out.println("Please enter the master password:");
String password = System.console().readLine();
new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8), true).write(password);
System.out.println("Password sent");
socket.close();
}Example 31
| Project: android-market-api-master File: Tools.java View source code |
public static String postUrl(String url, Map<String, String> params) throws IOException {
String data = "";
for (String key : params.keySet()) {
data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
}
data = data.substring(1);
//System.out.println(data);
// Make the connection to Authoize.net
URL aURL = new java.net.URL(url);
HttpURLConnection aConnection = (java.net.HttpURLConnection) aURL.openConnection();
try {
aConnection.setDoOutput(true);
aConnection.setDoInput(true);
aConnection.setRequestMethod("POST");
//aConnection.setAllowUserInteraction(false);
// POST the data
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
streamToAuthorize.write(data);
streamToAuthorize.flush();
streamToAuthorize.close();
// check error
int errorCode = aConnection.getResponseCode();
if (errorCode >= 400) {
InputStream errorStream = aConnection.getErrorStream();
try {
String errorData = streamToString(errorStream);
throw new HttpException(errorCode, errorData);
} finally {
errorStream.close();
}
}
// Get the Response
InputStream resultStream = aConnection.getInputStream();
try {
String responseData = streamToString(resultStream);
return responseData;
} finally {
resultStream.close();
}
} finally {
aConnection.disconnect();
}
}Example 32
| Project: ApkDownloader-master File: Tools.java View source code |
public static String postUrl(String url, Map<String, String> params) throws IOException {
String data = "";
for (String key : params.keySet()) {
data += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8");
}
data = data.substring(1);
//System.out.println(data);
// Make the connection to Authoize.net
URL aURL = new java.net.URL(url);
HttpURLConnection aConnection = (java.net.HttpURLConnection) aURL.openConnection();
try {
aConnection.setDoOutput(true);
aConnection.setDoInput(true);
aConnection.setRequestMethod("POST");
//aConnection.setAllowUserInteraction(false);
// POST the data
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(aConnection.getOutputStream());
streamToAuthorize.write(data);
streamToAuthorize.flush();
streamToAuthorize.close();
// check error
int errorCode = aConnection.getResponseCode();
if (errorCode >= 400) {
InputStream errorStream = aConnection.getErrorStream();
try {
String errorData = streamToString(errorStream);
throw new HttpException(errorCode, errorData);
} finally {
errorStream.close();
}
}
// Get the Response
InputStream resultStream = aConnection.getInputStream();
try {
String responseData = streamToString(resultStream);
return responseData;
} finally {
resultStream.close();
}
} finally {
aConnection.disconnect();
}
}Example 33
| Project: airball-for-android-master File: AirballDataSender.java View source code |
@SuppressLint("NewApi")
@Override
public void run() {
report("AirballDataSender run() ...");
try {
PrintWriter w = new PrintWriter(new OutputStreamWriter(mSocket.getOutputStream()));
while (true) {
if (!mSocket.isConnected()) {
return;
}
String msg = "" + System.currentTimeMillis();
report("AirballDataSender sending " + msg);
w.println(msg);
w.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
} catch (IOException e) {
report("AirballDataSender run() exiting: " + e);
}
}Example 34
| Project: ameba-master File: ClobStreamingProcess.java View source code |
/** {@inheritDoc} */
@Override
public void write(Clob entity, OutputStream output, Long pos, Long length) throws IOException {
Reader reader;
try {
reader = entity.getCharacterStream(pos, length);
} catch (SQLException e) {
throw new IOException(e);
}
try {
ReaderWriter.writeTo(reader, new OutputStreamWriter(output));
} finally {
IOUtils.closeQuietly(reader);
}
}Example 35
| Project: Android-Monkey-Adapter-master File: CommandHelper.java View source code |
public static ArrayList<String> exec(String command) throws InterruptedException {
ArrayList<String> out = new ArrayList<String>();
Process pro = null;
Runtime runTime = Runtime.getRuntime();
if (runTime == null) {
System.err.println("Create runtime false!");
}
try {
pro = runTime.exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
out.add(line);
}
input.close();
output.close();
pro.destroy();
} catch (IOException ex) {
Logger.getLogger(CommandHelper.class.getName()).log(Level.SEVERE, null, ex);
}
return out;
}Example 36
| Project: android-playlistr-master File: LogFile.java View source code |
public boolean saveLog(String tag, String message) {
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(new FileOutputStream(mFile, true));
StringBuilder log = new StringBuilder("\n---------------------------------------\n");
log.append(new SimpleDateFormat("dd-MM-yyyy hh:mm:ss :").format(new Date()));
log.append("\n\t");
log.append(tag);
log.append("\n\t");
log.append(message);
writer.append(log.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}Example 37
| Project: AndroidSnooper-master File: FileUtil.java View source code |
public String createLogFile(StringBuilder content, String fileName) {
FileOutputStream fileOutputStream = null;
String filePath = "";
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
if (file.exists()) {
file.delete();
}
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fileOutputStream);
myOutWriter.append(content.toString());
myOutWriter.close();
fileOutputStream.close();
filePath = file.getAbsolutePath();
} catch (FileNotFoundException e) {
Logger.e(TAG, "File Not Found Exception occurred while closing the output stream", e);
} catch (IOException e) {
Logger.e(TAG, "IO Exception occurred while closing the output stream", e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
Logger.e(TAG, "IO Exception occurred while closing the output stream", e);
}
}
return filePath;
}Example 38
| Project: AndroidStudyDemo-master File: GsonRequestBodyConverter.java View source code |
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
try {
gson.toJson(value, type, writer);
writer.flush();
} catch (IOException e) {
throw new AssertionError(e);
}
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}Example 39
| Project: android_explore-master File: Server.java View source code |
public void run() {
try {
//´´½¨ServerSocket
ServerSocket serverSocket = new ServerSocket(54321);
while (true) {
//½ÓÊܿͻ§¶ËÇëÇó
Socket client = serverSocket.accept();
System.out.println("accept");
try {
//½ÓÊÕ¿Í»§¶ËÏûÏ¢
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("read:" + str);
//Ïò·þÎñÆ÷·¢ËÍÏûÏ¢
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
out.println("server message");
//¹Ø±ÕÁ÷
out.close();
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
} finally {
//¹Ø±Õ
client.close();
System.out.println("close");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}Example 40
| Project: aq2o-master File: CsvMapWriter.java View source code |
/**
* DOES NOT CLOSE THE OUTPUT STREAM.
*
* @param map
* @param out
* @throws IOException
*/
public void write(Map<String, Object> map, OutputStream out) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
Iterator<Entry<String, Object>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object> entry = it.next();
String key = entry.getKey();
Object value = entry.getValue();
if (value != null && key != null) {
bw.write(key);
bw.write(",");
if (value.getClass().isAssignableFrom(Double.class) || value.getClass().isAssignableFrom(Long.class)) {
bw.write(dcf.format(value));
} else
bw.write(value.toString());
bw.newLine();
bw.flush();
}
}
}Example 41
| Project: ArretadoGames-master File: Settings.java View source code |
public static void save(FileIO files) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(files.writeFile(file)));
out.write(Boolean.toString(soundEnabled));
out.write("\n");
out.write(Boolean.toString(touchEnabled));
} catch (IOException e) {
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
}
}
}Example 42
| Project: Aspose_Slides_Java-master File: ExportingParagraphsTextToHTML.java View source code |
public static void main(String[] args) {
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExportingParagraphsTextToHTML.class);
// Load the presentation file
Presentation pres = new Presentation(dataDir + "DemoFile.pptx");
// Access the default first slide of presentation
ISlide slide = pres.getSlides().get_Item(0);
// Desired index
int index = 0;
// Accessing the added shape
IAutoShape ashape = (IAutoShape) slide.getShapes().get_Item(index);
try {
// Creating output HTML file
OutputStream os = new FileOutputStream(dataDir + "file.html");
Writer writer = new OutputStreamWriter(os, "UTF-8");
// Extracting first paragraph as HTML
// Writing Paragraphs data to HTML by providing paragraph starting index, total paragraphs to be copied
writer.write(ashape.getTextFrame().getParagraphs().exportToHtml(0, ashape.getTextFrame().getParagraphs().getCount(), null));
writer.close();
} catch (Exception fo) {
fo.printStackTrace();
}
}Example 43
| Project: BACKUP_FROM_SVN-master File: DefaultXmlWriter.java View source code |
public void write(Document doc, OutputStream outputStream) throws IOException {
try {
TransformerFactory factory = TransformerFactory.newInstance();
try {
factory.setAttribute("indent-number", 4);
} catch (Exception e) {
;
}
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//need to nest outputStreamWriter to get around JDK 5 bug. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8")));
} catch (TransformerException e) {
throw new IOException(e.getMessage());
}
}Example 44
| Project: Breakbulk-master File: TrigToJson.java View source code |
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
InputStream in = TrigToJson.class.getResourceAsStream("initialize.trig");
String input = IOUtils.toString(in);
Collection<Statement> statements = ReadWriteUtils.readStatements(input, RDFFormat.TRIG);
Writer writer = new OutputStreamWriter(new FileOutputStream("initialize.json"), "UTF-8");
ReadWriteUtils.writeStatements(statements, writer, RDFFormat.JSON);
writer.flush();
writer.close();
}Example 45
| Project: brouter-master File: ConfigHelper.java View source code |
public static void writeBaseDir(Context ctx, String baseDir) {
BufferedWriter bw = null;
try {
OutputStream configOutput = ctx.openFileOutput("config.dat", Context.MODE_PRIVATE);
bw = new BufferedWriter(new OutputStreamWriter(configOutput));
bw.write(baseDir);
bw.write('\n');
} catch (Exception e) {
} finally {
if (bw != null)
try {
bw.close();
} catch (Exception ee) {
}
}
}Example 46
| Project: building-microservices-master File: CloudS3Application.java View source code |
@PostConstruct
public void resourceAccess() throws IOException {
String location = "s3://" + this.bucket + "/file.txt";
WritableResource writeableResource = (WritableResource) this.resourceLoader.getResource(location);
FileCopyUtils.copy("Hello World!", new OutputStreamWriter(writeableResource.getOutputStream()));
Resource resource = this.resourceLoader.getResource(location);
System.out.println(FileCopyUtils.copyToString(new InputStreamReader(resource.getInputStream())));
}Example 47
| Project: cattle-master File: FreemarkerTemplate.java View source code |
@Override
public void execute(Map<String, Object> context, OutputStream os) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(os);
template.process(context, writer);
} catch (TemplateException e) {
log.error("Failed to run template for [{}]", resource.getName(), e);
throw new IOException(e);
} finally {
writer.flush();
}
}Example 48
| Project: cerb-impex-master File: XMLThread.java View source code |
@Override
public synchronized void start() {
Boolean isVerbose = Boolean.valueOf(Configuration.get("verbose", "false"));
String sExportEncoding = Configuration.get("exportEncoding", "ISO-8859-1");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(sExportEncoding);
format.setOmitEncoding(false);
OutputStream fileOutputStream = null;
XMLWriter writer = null;
try {
fileOutputStream = new FileOutputStream(this.fileName);
writer = new XMLWriter(new OutputStreamWriter(fileOutputStream, sExportEncoding), format);
writer.write(doc);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
StreamUtils.closeSilently(fileOutputStream);
doc.clearContent();
doc = null;
}
if (isVerbose)
System.out.println("Wrote " + this.fileName);
this.interrupt();
}Example 49
| Project: chinesesegmentor-master File: ReverseFeatureDict.java View source code |
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage <in> <out>");
System.exit(-1);
}
String featureFilename = args[0];
FSTObjectInput foi = null;
FeatureDict dict = null;
System.out.println("load featuredict from: " + featureFilename);
try {
foi = new FSTObjectInput(new FileInputStream(featureFilename));
dict = (FeatureDict) foi.readObject();
} finally {
if (foi != null) {
foi.close();
}
}
System.out.println(dict.size());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(args[1]), "UTF8"));
TObjectIntIterator<String> iter = dict.iterator();
int line = 0;
while (iter.hasNext()) {
iter.advance();
bw.write(iter.key() + "\t" + iter.value() + "\n");
line++;
}
System.out.println(line);
bw.close();
}Example 50
| Project: ciel-java-master File: PiReducer.java View source code |
@Override
public void invoke(InputStream[] fis, OutputStream[] fos, String[] args) {
try {
/**
* args: none.
*/
/**
* inputs: n files containing (long) numInside, (long) numOutside.
*/
long numInside = 0;
long numOutside = 0;
for (int i = 0; i < fis.length; ++i) {
DataInputStream in = new DataInputStream(fis[i]);
numInside += in.readLong();
numOutside += in.readLong();
in.close();
}
//compute estimated value
double actualResult;
try {
BigDecimal result = BigDecimal.valueOf(4).setScale(20).multiply(BigDecimal.valueOf(numInside)).divide(BigDecimal.valueOf(numInside + numOutside));
actualResult = result.doubleValue();
System.out.println("Result is: " + result.toPlainString());
} catch (Exception e) {
actualResult = Math.PI;
System.out.println("Java BigDecimal is being a pain...");
}
/**
* output: single file containing (double) result.
*/
OutputStreamWriter out = new OutputStreamWriter(fos[0]);
out.write(actualResult + "");
out.close();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}Example 51
| Project: cytoscape-d3-master File: D3NetworkWriter.java View source code |
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
if (taskMonitor != null) {
taskMonitor.setTitle("Writing to D3-Style JSON");
taskMonitor.setStatusMessage("Writing network in D3.js format...");
taskMonitor.setProgress(-1.0);
}
network2jsonMapper.writeValue(new OutputStreamWriter(outputStream, EncodingUtil.getEncoder()), network);
outputStream.close();
if (taskMonitor != null) {
taskMonitor.setStatusMessage("Success.");
taskMonitor.setProgress(1.0);
}
}Example 52
| Project: diirt-master File: JDBCSampleClient.java View source code |
public static void main(String[] args) throws Exception {
ServiceRegistry.getDefault().registerService(JDBCSampleService.create());
ServiceMethod method;
VTable table;
method = ServiceRegistry.getDefault().findServiceMethod("jdbcSample/insert");
Map<String, Object> arguments = new HashMap<>();
arguments.put("name", newVString("George", alarmNone(), timeNow()));
arguments.put("index", newVDouble(4.1, alarmNone(), timeNow(), displayNone()));
arguments.put("value", newVDouble(2.11, alarmNone(), timeNow(), displayNone()));
method.executeSync(arguments);
method = ServiceRegistry.getDefault().findServiceMethod("jdbcSample/query");
table = (VTable) method.executeSync(new HashMap<String, Object>()).get("result");
CSVIO io = new CSVIO();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(System.out);
io.export(table, outputStreamWriter);
outputStreamWriter.flush();
}Example 53
| Project: elexis-3-base-master File: JaxbUtil.java View source code |
public static ByteArrayOutputStream getOutputStreamForObject(Object jaxbObj) throws UnsupportedEncodingException, IOException, JAXBException {
ByteArrayOutputStream ret = new ByteArrayOutputStream();
OutputStreamWriter writer;
writer = new OutputStreamWriter(ret, "UTF-8");
JAXBContext jc = JAXBContext.newInstance(jaxbObj.getClass());
Marshaller m = jc.createMarshaller();
m.setProperty("jaxb.encoding", "UTF-8");
m.marshal(jaxbObj, writer);
writer.close();
return ret;
}Example 54
| Project: enzymeportal-master File: AbstractSitemapUrlRenderer.java View source code |
public void render(WebSitemapUrl url, OutputStreamWriter out, W3CDateFormat dateFormat, String additionalData) throws IOException {
out.write(" <url>\n");
out.write(" <loc>");
out.write(url.getUrl().toString());
out.write("</loc>\n");
if (url.getLastMod() != null) {
out.write(" <lastmod>");
out.write(dateFormat.format(url.getLastMod()));
out.write("</lastmod>\n");
}
if (url.getChangeFreq() != null) {
out.write(" <changefreq>");
out.write(url.getChangeFreq().toString());
out.write("</changefreq>\n");
}
if (url.getPriority() != null) {
out.write(" <priority>");
out.write(url.getPriority().toString());
out.write("</priority>\n");
}
if (additionalData != null)
out.write(additionalData);
out.write(" </url>\n");
}Example 55
| Project: epublib-master File: TextReplaceBookProcessor.java View source code |
public byte[] processHtml(Resource resource, Book book, String outputEncoding) throws IOException {
Reader reader = resource.getReader();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, Constants.CHARACTER_ENCODING);
for (String line : IOUtils.readLines(reader)) {
writer.write(processLine(line));
writer.flush();
}
return out.toByteArray();
}Example 56
| Project: ermaster-b-master File: AbstractTextTestDataCreator.java View source code |
@Override
protected void openFile() throws IOException {
File file = new File(this.exportTestDataSetting.getExportFilePath());
file.getParentFile().mkdirs();
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.exportTestDataSetting.getExportFilePath() + File.separator + this.testData.getName() + this.getFileExtention()), this.exportTestDataSetting.getExportFileEncoding())));
}Example 57
| Project: errbit-java-master File: NoticeSender.java View source code |
public void send(Notice notice) throws IOException {
HttpURLConnection connection = createConnection();
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), UTF);
marshaller.marshal(notice, writer);
writer.close();
if (connection.getResponseCode() != 200) {
throw new IOException("Notifier response code " + connection.getResponseCode());
}
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}Example 58
| Project: fastcatsearch-master File: SearchProxyTest.java View source code |
@Test
public void test() throws IOException {
String stringToReverse = URLEncoder.encode("", "UTF-8");
String urlString = "http://localhost:8090/search/json";
String paramString = "cn=sample&sn=1&ln=10&fl=title&se={title:약관으로}";
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(paramString);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString = null;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}Example 59
| Project: featurehouse_fstcomp_examples-master File: LogWriter.java View source code |
public void newChatLine(TextMessage msg) {
// TODO Auto-generated method stub
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log/Log_" + chatComp.getName().replaceAll("/", "-") + ".txt", true), "ISO-8859-1"));
String content = msg.getSender() + ">" + msg.getSettings() + ">" + msg.getContent() + "\n";
out.write(content, 0, content.length());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 60
| Project: folioxml-master File: SlxTransformerTest.java View source code |
public void XmlExport(String configName) throws IOException, InvalidMarkupException {
System.out.println("Starting");
FolioTokenReader ftr = new FolioTokenReader(new File(TestConfig.getFolioHlp().getFlatFilePath()));
File file = new File(TestConfig.getFolioHlp().getExportFile("Translation.slx", true));
FileOutputStream fos = new FileOutputStream(file);
try {
SlxRecordReader srr = new SlxRecordReader(new SlxTranslatingReader(ftr));
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<infobase>");
while (true) {
SlxRecord r = srr.read();
SlxToXmlTransformer gts = new SlxToXmlTransformer();
if (r == null)
break;
out.write(gts.convert(r).toXmlString(true));
}
out.write("\n</infobase>");
out.close();
} finally {
ftr.close();
fos.close();
}
}Example 61
| Project: gearman-java-master File: ClusterServlet.java View source code |
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
cfg.setClassForTemplateLoading(ClusterServlet.class, "templates");
cfg.setTemplateUpdateDelay(0);
try {
final OutputStream output = resp.getOutputStream();
OutputStreamWriter wr = new OutputStreamWriter(output);
if (serverConfiguration.getCluster() != null) {
cfg.getTemplate("cluster.ftl").process(new ClusterView(serverConfiguration.getCluster().getHazelcastInstance()), wr);
} else {
cfg.getTemplate("nocluster.ftl").process(null, wr);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}Example 62
| Project: GeoGig-master File: WriterRepresentation.java View source code |
@Override
public void write(OutputStream outputStream) throws IOException {
Writer writer = null;
if (getCharacterSet() != null) {
writer = new OutputStreamWriter(outputStream, getCharacterSet().getName());
} else {
// Use the default HTTP character set
writer = new OutputStreamWriter(outputStream, CharacterSet.UTF_8.getName());
}
write(writer);
writer.flush();
}Example 63
| Project: geoserver-2.0.x-master File: FilterFunction_freemarker.java View source code |
public Object evaluate(Object featureObj) {
try {
SimpleFeature feature = (SimpleFeature) featureObj;
String template = getExpression(0).evaluate(feature, String.class);
templateLoader.putTemplate("template", template);
Template t = templateConfig.getTemplate("template");
// t.setEncoding(charset.name());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(bos);
t.process(feature, w);
return bos.toString();
} catch (Exception e) {
throw new RuntimeException("Issues occurred processing the template", e);
}
}Example 64
| Project: gig-master File: WriterRepresentation.java View source code |
@Override
public void write(OutputStream outputStream) throws IOException {
Writer writer = null;
if (getCharacterSet() != null) {
writer = new OutputStreamWriter(outputStream, getCharacterSet().getName());
} else {
// Use the default HTTP character set
writer = new OutputStreamWriter(outputStream, CharacterSet.UTF_8.getName());
}
write(writer);
writer.flush();
}Example 65
| Project: grouperfish-master File: MapStreamer.java View source code |
public void write(OutputStream out) throws IOException {
final Writer writer = new BufferedWriter(new OutputStreamWriter(out, StreamTool.UTF8));
boolean first = true;
writer.write('{');
for (final Map.Entry<String, String> items : map.entrySet()) {
if (first) {
first = false;
} else {
writer.append(',');
writer.append('\n');
}
writer.append('"').append(JSONValue.escape(items.getKey())).append('"').append(':').append(' ').write(items.getValue());
}
writer.write('}');
writer.flush();
}Example 66
| Project: gwt-angular-master File: VelocityGenerator.java View source code |
void merge(Writer writer) {
Template template = VELOCITY_ENGINE.getTemplate(filename, ENCODING);
template.merge(velocityContext, writer);
if (System.getProperty("velocity.print") != null) {
try {
Writer w = new OutputStreamWriter(System.out);
template.merge(velocityContext, w);
w.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}Example 67
| Project: hadcom.utils-master File: GenerateEnvSingleTableTestFile.java View source code |
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
if (args.length != 3 || args[0].contains("-h")) {
System.out.println("GenerateTestFile <outputPath> <number of keys> <number of fields>");
System.out.println();
System.out.println("GenerateTestFile ./filename 100 10");
return;
}
String filename = args[0];
int numOfKeys = Integer.parseInt(args[1]);
int numOfFields = Integer.parseInt(args[2]);
Configuration config = new Configuration();
FileSystem hdfs = FileSystem.get(config);
FSDataOutputStream outputStream = hdfs.create(new Path(filename));
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(outputStream));
for (int i = 0; i < numOfKeys; i++) {
for (int j = 0; j < numOfFields; j++) {
//This will leave 20% of the fields empty for each key
if (Math.random() < .8) {
br.write("key-" + i + "|field-" + j + "|ValueFor" + i + "-" + j + "\n");
}
}
}
br.close();
}Example 68
| Project: Hadoop-example1-WordCount-master File: Create.java View source code |
public int run(String[] args) throws Exception {
int size = Integer.parseInt(args[0]);
size *= // MB
1024 * // MB
1024;
Path f = new Path(args[1]);
System.out.println("create " + f);
FileSystem fs = FileSystem.get(getConf());
FSDataOutputStream os = fs.create(f);
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
try {
int n = 0;
for (int i = 0; ; i++) {
String s = data(i);
bw.write(s);
bw.write('\n');
n += s.getBytes("UTF-8").length + 1;
if (n >= size) {
break;
}
}
} finally {
bw.close();
}
} finally {
os.close();
}
return 0;
}Example 69
| Project: hapi-fhir-master File: SyncUtil.java View source code |
public static void main(String[] args) throws Exception {
FhirContext ctx = FhirContext.forDstu2();
String fileName = "src/main/resources/vs/dstu2/all-valuesets-bundle.xml";
FileReader fr = new FileReader(fileName);
Bundle b = ctx.newXmlParser().parseResource(Bundle.class, fr);
for (Entry nextEntry : b.getEntry()) {
BaseResource nextRes = (BaseResource) nextEntry.getResource();
nextRes.setText(new NarrativeDt());
}
File f = new File(fileName);
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(f, false), "UTF-8");
ctx.newXmlParser().encodeResourceToWriter(b, fw);
fw.close();
ourLog.info("Fixed {} valuesets", b.getEntry().size());
}Example 70
| Project: Haven-and-Hearth-client-modified-by-Ender-master File: IdentServer.java View source code |
public void run() {
if (socket == null)
return;
try {
Socket soc = socket.accept();
soc.setSoTimeout(60000);
BufferedReader reader = new BufferedReader(new InputStreamReader(soc.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
String line = reader.readLine();
if (line != null) {
writer.write(line + " : USERID : UNIX : " + login + "\r\n");
writer.flush();
writer.close();
reader.close();
}
socket.close();
} catch (IOException e) {
}
}Example 71
| Project: hudson_plugins-master File: ExecuteFilePath.java View source code |
/**
* Parse the file.
* @throws IOException if there is a problem.
* @throws InterruptedException if interrupted.
*/
public void execute() throws IOException, InterruptedException {
boolean seenException = false;
FilePath f = targetDir.child(filename);
PrintWriter w = new PrintWriter(new BufferedWriter(new OutputStreamWriter(f.write(), // ? for html //
"UTF-8")));
try {
ex.execute(w);
} catch (IOException ex) {
seenException = true;
throw ex;
} finally {
CloseUtil.close(w, seenException);
}
}Example 72
| Project: j-road-master File: FileUtil.java View source code |
public static Writer createAndGetOutputStream(String typename, String outputPath) throws IOException {
if (typename.indexOf('$') > 0) {
System.out.println(typename);
typename = typename.substring(0, typename.lastIndexOf('.')) + "." + typename.substring(typename.indexOf('$') + 1);
}
File file = new File(outputPath, typename.replace('.', File.separatorChar) + ".java");
file.getParentFile().mkdirs();
file.createNewFile();
OutputStream os = new FileOutputStream(file);
return new OutputStreamWriter(os, Charset.forName("UTF-8"));
}Example 73
| Project: JavaQA-master File: GZIPResponseWrapper.java View source code |
public PrintWriter getWriter() throws IOException {
if (writer != null) {
return (writer);
}
if (stream != null) {
throw new IllegalStateException("getOutputStream() has already been called!");
}
stream = createOutputStream();
// BUG FIX 2003-12-01 Reuse content's encoding, don't assume UTF-8
writer = new PrintWriter(new OutputStreamWriter(stream, origResponse.getCharacterEncoding()));
return (writer);
}Example 74
| Project: jeboorker-master File: TextReplaceBookProcessor.java View source code |
public byte[] processHtml(Resource resource, Book book, String outputEncoding) throws IOException {
Reader reader = resource.getReader();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, Constants.ENCODING);
for (String line : IOUtils.readLines(reader)) {
writer.write(processLine(line));
writer.flush();
}
return out.toByteArray();
}Example 75
| Project: jetstream-master File: RESTHelper.java View source code |
public static String httpPost(String urlString, String data) throws IOException {
URL url = new URL(urlString);
URLConnection uc = url.openConnection();
uc.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream());
InputStream in = null;
try {
if (data != null) {
writer.write(data);
}
writer.flush();
// Get the response
in = uc.getInputStream();
return CommonUtils.getStreamAsString(in, "\n");
} finally {
writer.close();
if (in != null) {
in.close();
}
}
}Example 76
| Project: JFOA-master File: Testclz.java View source code |
/**
* @param args
*/
public static void main(String[] args) {
// URL url=Testclz.class.getResource("/");
// System.out.println(url.toString());
// System.out.println(MD5.getMD5ofStr("123456").toLowerCase());
/*
try{
Process p= Runtime.getRuntime().exec("ipconfig");
BufferedReader reader=new BufferedReader(new InputStreamReader( p.getInputStream(),"GBK"));
String s;
while((s=reader.readLine())!=null){
System.out.println(s);
}
}catch(Exception e){
e.printStackTrace();
}*/
String classpath = Testclz.class.getResource("/").getPath();
String libDir = classpath.replace("classes", "lib");
File libDirf = new File(libDir);
StringBuffer cmd = new StringBuffer("rhc java -classpath \"");
for (String f : libDirf.list()) {
if (f.endsWith(".jar")) {
cmd.append("../lib/");
cmd.append(f);
cmd.append(";");
}
}
cmd.append("\" -agentlib:D:/java/classloader Server");
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(classpath + "/run.bat"), "UTF-8");
out.write(cmd.toString());
out.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("æ£å¸¸è°ƒç”¨");
}Example 77
| Project: josm-master File: OsmDataSessionExporter.java View source code |
@Override
protected void addDataFile(OutputStream out) {
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
layer.data.getReadLock().lock();
try {
w.writeLayer(layer);
w.flush();
} finally {
layer.data.getReadLock().unlock();
}
}Example 78
| Project: KingTV-master File: GsonRequestBodyConverter.java View source code |
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}Example 79
| Project: kura-master File: test.java View source code |
public static void main(String[] args) throws Exception {
///java cx.ath.matthew.io.findeof")));
PrintWriter out = new PrintWriter(new OutputStreamWriter(new ExecOutputStream(System.out, "xsltproc mcr.xsl -")));
out.println("<?xml version='1.0'?>");
out.println(" <?xml-stylesheet href='style/mcr.xsl' type='text/xsl'?>");
out.println(" <mcr xmlns:xi='http://www.w3.org/2001/XInclude'>");
out.println(" <title>TEST</title>");
out.println(" <content title='TEST'>");
out.println("hello, he is helping tie up helen's lemmings");
out.println("we are being followed and we break out");
out.println(" </content>");
out.println(" </mcr>");
out.close();
}Example 80
| Project: LD-FusionTool-master File: NTuplesWriterTest.java View source code |
@Test
public void writesCorrectlyAllValueTypes() throws Exception {
// Arrange
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Act
NTuplesWriter nTuplesWriter = new NTuplesWriter(new OutputStreamWriter(outputStream));
try {
nTuplesWriter.writeTuple(VF.createURI("http://uri1"), VF.createBNode("bnode1"), VF.createLiteral("literal"), VF.createLiteral(123));
nTuplesWriter.writeTuple(VF.createURI("http://uri2"));
nTuplesWriter.writeTuple(VF.createURI("http://uri3"), VF.createURI("http://uri4"));
} finally {
nTuplesWriter.close();
}
// Assert
String expectedResult = "<http://uri1> _:bnode1 \"literal\" \"123\"^^<http://www.w3.org/2001/XMLSchema#int> .\n" + "<http://uri2> .\n" + "<http://uri3> <http://uri4> .\n";
String result = outputStream.toString();
assertThat(result, is(expectedResult));
}Example 81
| Project: LEADT-master File: LogWriter.java View source code |
public void newChatLine(TextMessage msg) {
// TODO Auto-generated method stub
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("log/Log_" + chatComp.getName().replaceAll("/", "-") + ".txt", true), "ISO-8859-1"));
String content = msg.getSender() + ">" + msg.getSettings() + ">" + msg.getContent() + "\n";
out.write(content, 0, content.length());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 82
| Project: lightning-master File: JenkinsReporter.java View source code |
private void writeJenkinsFile(String summary) {
try (FileOutputStream fos = new FileOutputStream("lightning-jenkins.properties")) {
Properties props = new Properties();
props.setProperty("result.string", summary);
OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
props.store(out, "In Jenkins Build Name Setter Plugin, define build name as: ${BUILD_NUMBER} - ${PROPFILE,file=\"lightning-jenkins.properties\",property=\"result.string\"}");
} catch (IOException e) {
throw new JenkinsReportGenerationException(e);
}
}Example 83
| Project: logbook-master File: ShipInfoToCSV.java View source code |
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
boolean init = MasterData.INIT_COMPLETE;
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream("shipInfo.csv"), "MS932");
fw.write(StringUtils.join(new String[] { "å??å‰?", "艦ID", "タイプID", "タイプå??", "æ”¹é€ Lv", "æ”¹é€ å¾Œã?®è‰¦ID", "Flagship", "Maxå¼¾", "Max燃料" }, ','));
fw.write("\n");
for (int key : Ship.getMap().keySet()) {
ShipInfoDto dto = Ship.get(key);
if (dto.getName().length() > 0) {
fw.write(StringUtils.join(new String[] { dto.getName(), Integer.toString(dto.getShipId()), Integer.toString(dto.getStype()), dto.getType(), Integer.toString(dto.getAfterlv()), Integer.toString(dto.getAftershipid()), dto.getFlagship(), Integer.toString(dto.getMaxBull()), Integer.toString(dto.getMaxFuel()) }, ','));
fw.write("\n");
}
}
fw.close();
}Example 84
| Project: MDroid-master File: MoodleRestCall.java View source code |
/**
* Executes the Moodle Rest call with the set parameters
*
* @param restUrl
* Moodle url to make rest calls
* @param params
* Params for the rest call
* @return InputStreamReader to read the content from
*
* @author Praveen Kumar Pendyala (praveen@praveenkumar.co.in)
*/
public InputStreamReader fetchContent(String restUrl, String params) {
Log.d(DEBUG_TAG, restUrl + params);
HttpURLConnection con;
try {
con = (HttpURLConnection) new URL(restUrl + params).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/xml");
con.setRequestProperty("Content-Language", "en-US");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write("");
writer.flush();
writer.close();
return new InputStreamReader(con.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 85
| Project: mecha-master File: UpdateBookRequest.java View source code |
@Override
public void writeBody(JsonEntityWriterProvider provider, OutputStream stream) throws IOException {
JsonWriter writer = null;
try {
if (stream != null) {
writer = new JsonWriter(new OutputStreamWriter(stream, Charset.defaultCharset()));
provider.get(Book.class).write(writer, book);
}
} finally {
Closeables.closeSilently(writer);
}
}Example 86
| Project: mechanoid-master File: UpdateBookRequest.java View source code |
@Override
public void writeBody(JsonEntityWriterProvider provider, OutputStream stream) throws IOException {
JsonWriter writer = null;
try {
if (stream != null) {
writer = new JsonWriter(new OutputStreamWriter(stream, Charset.defaultCharset()));
provider.get(Book.class).write(writer, book);
}
} finally {
Closeables.closeSilently(writer);
}
}Example 87
| Project: micro-server-master File: ReactiveResponse.java View source code |
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
ReactiveSeq.fromPublisher(json).map(JacksonUtil::serializeToJson).forEach(ExceptionSoftener.softenConsumer( json -> {
writer.write(json);
writer.write("\n");
}), e -> {
}, ExceptionSoftener.softenRunnable(() -> writer.flush()));
writer.flush();
}Example 88
| Project: minecraft-roguelike-master File: ConfigFileWriter.java View source code |
/**
* Writes a particular set of configurations to
* a particular file according to a particular
* representation.
*
* \param [in] filename
* The name of the file to which configuration
* data shall be written.
* \param [in] config
* The configurations which shall be written to
* the given file.
* \param [in] writer
* A ConfigurationParser which implements the
* desired strategy for representing configuration
* data in the file.
*/
public static void Write(String filename, ConfigurationProvider config, ConfigurationParser writer) throws Exception {
// Open file for writing
FileOutputStream stream = new FileOutputStream(filename, true);
// Truncate file in case it already
// existed
stream.getChannel().truncate(0);
// Create a writer
BufferedWriter buffered = new BufferedWriter(new OutputStreamWriter(stream));
// Write all configurations
for (Configuration c : config) writer.Write(buffered, c);
// Close the stream and flush out
// all written configurations
buffered.close();
}Example 89
| Project: mock-http-server-master File: HttpResponseFileWriterImpl.java View source code |
private void writeResponse(final HttpResponse httpResponse, final File httpResponseFile) throws IOException {
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(httpResponseFile), "UTF-8"));
try {
writer.write("[HttpCode]");
writer.newLine();
writer.write(String.valueOf(httpResponse.getHttpCode()));
writer.newLine();
writer.write("[ContentType]");
writer.newLine();
if (!StringUtils.isBlank(httpResponse.getContentType())) {
writer.write(httpResponse.getContentType());
}
writer.newLine();
} finally {
writer.close();
}
}Example 90
| Project: molgenis-master File: CsvHttpMessageConverter.java View source code |
@Override
protected void writeInternal(EntityCollection entities, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
OutputStreamWriter out = new OutputStreamWriter(outputMessage.getBody(), getCharset(outputMessage.getHeaders()));
CsvWriter writer = new CsvWriter(out);
try {
writer.writeAttributeNames(entities.getAttributeNames());
writer.add(entities.stream());
} finally {
IOUtils.closeQuietly(writer);
}
}Example 91
| Project: mssqldiff-master File: SchemaCsvWriter.java View source code |
public void write(List<SchemaCsv> data) {
try {
OutputStream output = new FileOutputStream(path);
Writer iwriter = new OutputStreamWriter(output, "UTF-8");
CSVWriter writer = new CSVWriter(iwriter, ',', '"');
try {
writer.writeNext(SchemaCsv.COLUMNS);
for (SchemaCsv csv : data) {
String[] values = new String[SchemaCsv.COLUMNS.length];
values[0] = csv.getObjectType();
values[1] = csv.getTableName();
values[2] = csv.getColumnName();
values[3] = csv.getColumnType();
values[4] = Integer.toString(csv.getLength());
values[5] = Boolean.toString(csv.isPk());
values[6] = Boolean.toString(csv.isIdentity());
values[7] = Boolean.toString(csv.isNullable());
values[8] = csv.getDefaultValue();
values[9] = csv.getTableDescription();
values[10] = csv.getColumnDescription();
values[11] = csv.getUserName();
values[12] = Boolean.toString(csv.isCanSelect());
values[13] = Boolean.toString(csv.isCanInsert());
values[14] = Boolean.toString(csv.isCanUpdate());
values[15] = Boolean.toString(csv.isCanDelete());
writer.writeNext(values);
}
} finally {
writer.close();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 92
| Project: MULE-master File: CharSetUtils.java View source code |
public static String defaultCharsetName() {
try {
if (SystemUtils.IS_JAVA_1_4) {
return new OutputStreamWriter(new ByteArrayOutputStream()).getEncoding();
} else {
Class target = Charset.class;
Method defaultCharset = target.getMethod("defaultCharset", ArrayUtils.EMPTY_CLASS_ARRAY);
Charset cs = (Charset) defaultCharset.invoke(target, (Object[]) null);
return cs.name();
}
} catch (Exception ex) {
throw new Error(ex);
}
}Example 93
| Project: mycontainer-master File: EngineResponseWrapper.java View source code |
@Override
public PrintWriter getWriter() throws IOException {
if (out != null) {
throw new RuntimeException("getOutputStream() was called");
}
if (writer == null) {
String characterEncoding = getResponse().getCharacterEncoding();
OutputStreamWriter wrt = new OutputStreamWriter(buffer, characterEncoding);
writer = new PrintWriter(wrt);
}
return writer;
}Example 94
| Project: MyLibrary-master File: DiskCacheEntry.java View source code |
/**
* å?‘DiskLruCache.Editorä¸å†™å…¥æ•°æ?®
*/
public final void writeTo(DiskLruCache.Editor editor) throws IOException {
OutputStream out = editor.newOutputStream(entry);
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(out, Charsets.UTF_8));
write(writer);
} finally {
IoUtil.closeQuietly(writer);
IoUtil.closeQuietly(out);
}
}Example 95
| Project: mysql_perf_analyzer-master File: MailUtil.java View source code |
/**
* A simple mail client to use shell command to send mail
* @param receiver
* @param subject
* @param msg
* @return
*/
public static boolean sendMail(String receiver, String subject, String msg) {
//or mail, which send long body as attachment
String mailCommand = "mailx";
String os = System.getProperty("os.name");
if (os != null && os.toUpperCase().contains("WIN"))
return false;
logger.info("Sending email to " + receiver + " regarding " + subject);
String[] cmd = { mailCommand, "-s", subject, receiver };
try {
Process p = Runtime.getRuntime().exec(cmd);
Writer w = new java.io.OutputStreamWriter(p.getOutputStream());
w.append(msg);
w.flush();
w.close();
p.waitFor();
logger.info("Mail exitValue=" + p.exitValue());
return true;
} catch (Exception ex) {
logger.log(Level.SEVERE, "Error when send mail", ex);
}
return false;
}Example 96
| Project: nextprot-api-master File: GenerateUserDTD.java View source code |
/**
* This method should be executed every times the db schema change.
* The schema is defined in main/resources/db.migration/*.sql.
* The generated file user.dtd should go
* @throws Exception
*/
@Test
public void generateUserDTD() throws Exception {
IDatabaseConnection connection = new DatabaseConnection(dsLocator.getUserDataSource().getConnection(), "np_users");
// write DTD file
IDataSet dataSet = connection.createDataSet();
Writer out = new OutputStreamWriter(new FileOutputStream(dtdFile));
FlatDtdWriter datasetWriter = new FlatDtdWriter(out);
datasetWriter.setContentModel(FlatDtdWriter.CHOICE);
datasetWriter.write(dataSet);
}Example 97
| Project: ngmon-master File: Sensor.java View source code |
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = new Socket("localhost", 5000);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
int i = 10000;
while (i > 0) {
Thread.sleep(1);
i--;
String json = "{\"Event\":{\"occurrenceTime\":\"" + ISO8601Utils.format(new Date(System.currentTimeMillis()), true) + "\",\"hostname\":\"domain.localhost.cz\",\"type\":\"org.linux.cron.Started\",\"application\":\"Cron\",\"process\":\"cron\",\"processId\":\"4219\",\"severity\":5,\"priority\":4,\"Payload\":{\"schema\":\"http://www.linux.org/schema/monitoring/cron/3.1/events.xsd\",\"schemaVersion\":\"3.1\",\"value\":4648,\"value2\":\"Fax4x46aeEF%aax4x%46aeEF\"}}}";
out.write(json);
out.newLine();
out.flush();
}
out.close();
socket.close();
}Example 98
| Project: ocr-tools-master File: TextMerger.java View source code |
@Override
public void merge(List<InputStream> inputs, OutputStream output) {
try {
OutputStreamWriter osw = new OutputStreamWriter(output, "UTF-8");
// Ascii page break dec 12, hex 0c
char pb = (char) 12;
// Use the platform dependent separator here
String seperator = System.getProperty("line.separator");
int f = 0;
while (f < inputs.size()) {
InputStreamReader isr = new InputStreamReader(inputs.get(f), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
osw.write(line);
osw.write(seperator);
}
//osw.write(pb);
br.close();
isr.close();
f++;
}
osw.close();
} catch (IOException e) {
throw new IllegalStateException("Error while merging files.", e);
}
}Example 99
| Project: OCRaptor-master File: XMLTools.java View source code |
/**
*
*
* @param doc
* @param out
*
* @throws IOException
* @throws TransformerException
*/
public static void printDocument(Document doc, OutputStream out) throws IOException, TransformerException {
// printDocument(w3c.doc, new FileOutputStream(new
// File("/home/foo/a/git2/xoj2pdf.xml")));
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "UTF-8")));
}Example 100
| Project: olca-modules-master File: AbstractExport.java View source code |
public void run(File file, IDatabase database) {
CsvPreference pref = new CsvPreference.Builder('"', ';', "\n").build();
try (FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(fos, "utf-8");
BufferedWriter buffer = new BufferedWriter(writer);
CsvListWriter csvWriter = new CsvListWriter(buffer, pref)) {
doIt(csvWriter, database);
} catch (Exception e) {
log.error("failed to write file " + file, e);
}
}Example 101
| Project: OpenNotification-master File: EscadaListener.java View source code |
public void run() {
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket socket = ss.accept();
InetAddress escadaAddress = socket.getInetAddress();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
out.println("220");
String line = in.readLine();
if (line.indexOf("221") < 0) {
BrokerFactory.getLoggingBroker().logWarn("Got a bad eSCADA input from " + escadaAddress + ". Dropping connection");
} else {
// TODO: Connect to eSCADA
}
}
} catch (IOException e) {
BrokerFactory.getLoggingBroker().logError(e);
}
}