Java Code Examples for java.io.OutputStreamWriter#write()

The following examples show how to use java.io.OutputStreamWriter#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CsvInputFormatTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testPojoTypeWithMappingInformation() throws Exception {
	File tempFile = File.createTempFile("CsvReaderPojoType", "tmp");
	tempFile.deleteOnExit();
	tempFile.setWritable(true);

	OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile));
	wrt.write("123,3.123,AAA,BBB\n");
	wrt.write("456,1.123,BBB,AAA\n");
	wrt.close();

	@SuppressWarnings("unchecked")
	PojoTypeInfo<PojoItem> typeInfo = (PojoTypeInfo<PojoItem>) TypeExtractor.createTypeInfo(PojoItem.class);
	CsvInputFormat<PojoItem> inputFormat = new PojoCsvInputFormat<PojoItem>(new Path(tempFile.toURI().toString()), typeInfo, new String[]{"field1", "field3", "field2", "field4"});

	inputFormat.configure(new Configuration());
	FileInputSplit[] splits = inputFormat.createInputSplits(1);

	inputFormat.open(splits[0]);

	validatePojoItem(inputFormat);
}
 
Example 2
Source File: ACHWriter.java    From jach with Apache License 2.0 5 votes vote down vote up
private void writeLine(OutputStreamWriter writer, String line, boolean withLineSeparator) throws IOException {
    ++lines;
    writer.write(line);
    if (withLineSeparator) {
        writer.write(LINE_SEPARATOR);
    }
}
 
Example 3
Source File: Template.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private OutputStreamWriter getAllArrayAttributes(SourceBeanAttribute sb, OutputStreamWriter ow) {
	OutputStreamWriter toReturn = ow;

	try {
		if (sb.getValue() instanceof SourceBean) {
			SourceBean sbSubConfig = (SourceBean) sb.getValue();

			List containedSB = sbSubConfig.getContainedSourceBeanAttributes();
			int numberOfSb = containedSB.size();
			int sbCounter = 1;
			// standard tag attributes
			for (int i = 0; i < containedSB.size(); i++) {
				SourceBeanAttribute object = (SourceBeanAttribute) containedSB.get(i);
				Object o = object.getValue();
				SourceBean sb1 = SourceBean.fromXMLString(o.toString());
				String v = sb1.getCharacters();
				if (v != null) {
					toReturn.write(v + "\n");

				} else {
					// attributes

					toReturn.write("{ 	\n");
					List atts = sb1.getContainedAttributes();
					toReturn = getAllAttributes(object, toReturn);
					toReturn.write("} 	\n");
				}
				if (i != containedSB.size() - 1) {
					toReturn.write("       , ");
				}
			}

		}
	} catch (Exception e) {
		logger.error("Error while defining json chart template: " + e.getMessage());
	}
	return toReturn;
}
 
Example 4
Source File: GraphCreationWithCsvITCase.java    From flink with Apache License 2.0 5 votes vote down vote up
private FileInputSplit createTempFile(String content) throws IOException {
	File tempFile = File.createTempFile("test_contents", "tmp");
	tempFile.deleteOnExit();

	OutputStreamWriter wrt = new OutputStreamWriter(
			new FileOutputStream(tempFile), Charset.forName("UTF-8")
	);
	wrt.write(content);
	wrt.close();

	return new FileInputSplit(0, new Path(tempFile.toURI().toString()), 0,
						tempFile.length(), new String[] {"localhost"});
}
 
Example 5
Source File: Parser.java    From pysonar2 with Apache License 2.0 5 votes vote down vote up
private boolean sendCommand(String cmd, @NotNull Process pythonProcess) {
    try {
        OutputStreamWriter writer = new OutputStreamWriter(pythonProcess.getOutputStream());
        writer.write(cmd);
        writer.write("\n");
        writer.flush();
        return true;
    } catch (Exception e) {
        $.msg("\nFailed to send command to interpreter: " + cmd);
        return false;
    }
}
 
Example 6
Source File: OmahaClient.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the request to the server.
 */
private void sendRequestToServer(HttpURLConnection urlConnection, String xml)
        throws RequestFailureException {
    try {
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(xml, 0, xml.length());
        writer.close();
        checkServerResponseCode(urlConnection);
    } catch (IOException e) {
        throw new RequestFailureException("Failed to write request to server: ", e);
    }
}
 
Example 7
Source File: DHttpUtils.java    From JApiDocs with Apache License 2.0 5 votes vote down vote up
/**
 * send post request
 *
 * @return
 * @throws IOException
 */
public static DHttpResponse httpPost(DHttpRequest request) throws IOException{

    URL url = new URL(request.getUrl());
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("POST");
    httpConn.setInstanceFollowRedirects(request.isAutoRedirect());

    Map<String,String> headers = request.getHeaders();
    if(headers != null){
        for(Map.Entry<String, String> headerEntry : headers.entrySet()){
            httpConn.addRequestProperty(headerEntry.getKey(),  headerEntry.getValue());
        }
    }

    StringBuffer requestParams = new StringBuffer();
    Map<String, String> params = request.getParams();
    if (params != null && params.size() > 0) {
        httpConn.setDoOutput(true);

        Iterator<String> paramIterator = params.keySet().iterator();
        while (paramIterator.hasNext()) {
            String key = paramIterator.next();
            String value = params.get(key);
            requestParams.append(URLEncoder.encode(key, "UTF-8"));
            requestParams.append("=").append(
                    URLEncoder.encode(value, "UTF-8"));
            requestParams.append("&");
        }

        // sends POST data
        OutputStreamWriter writer = new OutputStreamWriter(
                httpConn.getOutputStream());
        writer.write(requestParams.toString());
        writer.flush();
    }


    return toResponse(httpConn);
}
 
Example 8
Source File: PosDataLoader.java    From DeepDriver with Apache License 2.0 5 votes vote down vote up
public void saveDictWords(String fileName) throws IOException {
	File file = new File(fileName);
	OutputStreamWriter writer = new OutputStreamWriter(
			new FileOutputStream(file), DEFAULT_ENCODE);
	for (String key : strMap.keySet()) {
		writer.write(key + "\t" + strMap.get(key) + "\n");
	}
	writer.close();
}
 
Example 9
Source File: RunnerRestCreateCluster.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
     OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
     wr.write("name=" + ((CommandTarget)command).target);
     wr.flush();
     wr.close();
}
 
Example 10
Source File: CsvInputFormatTest.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuotedStringParsingWithIncludeFields() throws Exception {
	final String fileContent = "\"20:41:52-1-3-2015\"|\"Re: Taskmanager memory error in Eclipse\"|" +
			"\"Blahblah <[email protected]>\"|\"blaaa|\"blubb\"";

	final File tempFile = File.createTempFile("CsvReaderQuotedString", "tmp");
	tempFile.deleteOnExit();
	tempFile.setWritable(true);

	OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tempFile));
	writer.write(fileContent);
	writer.close();

	TupleTypeInfo<Tuple2<String, String>> typeInfo = TupleTypeInfo.getBasicTupleTypeInfo(String.class, String.class);
	CsvInputFormat<Tuple2<String, String>> inputFormat = new TupleCsvInputFormat<Tuple2<String, String>>(new Path(tempFile.toURI().toString()), typeInfo, new boolean[]{true, false, true});

	inputFormat.enableQuotedStringParsing('"');
	inputFormat.setFieldDelimiter("|");
	inputFormat.setDelimiter('\n');

	inputFormat.configure(new Configuration());
	FileInputSplit[] splits = inputFormat.createInputSplits(1);

	inputFormat.open(splits[0]);

	Tuple2<String, String> record = inputFormat.nextRecord(new Tuple2<String, String>());

	assertEquals("20:41:52-1-3-2015", record.f0);
	assertEquals("Blahblah <[email protected]>", record.f1);
}
 
Example 11
Source File: SvmORLearner.java    From jatecs with GNU General Public License v3.0 5 votes vote down vote up
static void generateTestData(String outFile, IIndex index, int docID)
        throws IOException {
    File dir = new File(outFile).getParentFile();
    if (!dir.exists())
        dir.mkdirs();

    FileOutputStream os = new FileOutputStream(outFile);
    OutputStreamWriter out = new OutputStreamWriter(os);

    StringBuilder b = new StringBuilder();
    b.append("0");

    IIntIterator itFeats = index.getContentDB().getDocumentFeatures(docID);
    while (itFeats.hasNext()) {
        int featID = itFeats.next();
        double score = index.getWeightingDB().getDocumentFeatureWeight(
                docID, featID);
        if (score == 0)
            continue;

        b.append(" " + (featID + 1) + ":" + score);
    }

    b.append(Os.newline());

    out.write(b.toString());

    out.close();
}
 
Example 12
Source File: ChangeCharActivity.java    From bleTester with Apache License 2.0 5 votes vote down vote up
private void saveResualt(String result) {
	// TODO Auto-generated method stub
	if (result.isEmpty()) {
		Toast.makeText(this, "û�пɱ�������ݣ�", Toast.LENGTH_SHORT).show();
	} else {
		try {
			File file = new File(Environment.getExternalStorageDirectory(),
					"BLElog" + System.currentTimeMillis() + ".txt");
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (!file.exists())
				file.createNewFile();
			FileOutputStream out = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(out);
			writer.write(result);
			writer.flush();
			writer.close();
			out.close();
			Toast.makeText(
					ChangeCharActivity.this,
					"BLElog" + System.currentTimeMillis()
							+ ".txt�ļ��ɹ����浽SD����Ŀ¼��", Toast.LENGTH_SHORT)
					.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 13
Source File: UnicodeTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void generateSource(String thisClass, String otherClass) throws Exception {
    File file = new File(UnicodeTestSrc, thisClass + JAVA_FILE_EXT);
    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
    out.write("public class " + thisClass + " {\n");
    out.write("    public static void main(String[] args) {\n");
    out.write("        if (!" + otherClass + "." + otherClass.toLowerCase() + "().equals(\"" + otherClass + "\")) {\n");
    out.write("            throw new RuntimeException();\n");
    out.write("        }\n");
    out.write("    }\n");
    out.write("    public static String " + thisClass.toLowerCase() + "() {\n");
    out.write("        return \"" + thisClass + "\";\n");
    out.write("    }\n");
    out.write("}\n");
    out.close();
}
 
Example 14
Source File: URLEncoder.java    From kkFileView with Apache License 2.0 5 votes vote down vote up
/**
 * 将URL中的字符串编码为%形式
 *
 * @param path 需要编码的字符串
 * @param charset 编码
 *
 * @return 编码后的字符串
 */
public String encode(String path, Charset charset) {

	int maxBytesPerChar = 10;
	final StringBuilder rewrittenPath = new StringBuilder(path.length());
	ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
	OutputStreamWriter writer = new OutputStreamWriter(buf, charset);

	int c;
	for (int i = 0; i < path.length(); i++) {
		c = path.charAt(i);
		if (safeCharacters.get(c)) {
			rewrittenPath.append((char) c);
		} else if (encodeSpaceAsPlus && c == ' ') {
			// 对于空格单独处理
			rewrittenPath.append('+');
		} else {
			// convert to external encoding before hex conversion
			try {
				writer.write((char) c);
				writer.flush();
			} catch (IOException e) {
				buf.reset();
				continue;
			}

			byte[] ba = buf.toByteArray();
			for (int j = 0; j < ba.length; j++) {
				// Converting each byte in the buffer
				byte toEncode = ba[j];
				rewrittenPath.append('%');
				HexUtil.appendHex(rewrittenPath, toEncode, false);
			}
			buf.reset();
		}
	}
	return rewrittenPath.toString();
}
 
Example 15
Source File: Authentication.java    From pivaa with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Save username and password to external file
 * @param context
 * @param username
 * @param password
 * @return boolean
 */
public boolean saveLoginInfoExternalStorage(Context context, String username, String password) {
    if (isExternalStorageWritable()) {
        Log.i( "htbridge", "saveLoginInfoExternalStorage: writable, all ok!");
        Log.i( "htbridge", "getExternalStorageDirectory = " + Environment.getExternalStorageDirectory());
        Log.i( "htbridge", "getExternalStoragePublicDirectory = " + context.getExternalFilesDir(null) );



        String filename = context.getExternalFilesDir(null) + "/credentials.dat";

        Log.i( "htbridge", "saveLoginInfoExternalStorage: username = " + username + " | password = " + password);
        Log.i( "htbridge", "saveLoginInfoExternalStorage: opening for writing " + filename);

        File file = new File(context.getExternalFilesDir(null), "/credentials.dat");

        Log.i( "htbridge", "saveLoginInfoExternalStorage: opening for reading " + filename);

        try {
            String content = username + ":" + password + "\n";

            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

            myOutWriter.write(content);
            myOutWriter.close();
            fOut.flush();
            fOut.close();

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }


        return true;
    } else {
        return false;
    }
}
 
Example 16
Source File: RawStore.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void logHistory(OutputStreamWriter historyFile, String msg) throws IOException
{
	Date d = new Date();
	historyFile.write(d.toString() + ":" + msg + "\n");
	historyFile.flush();
}
 
Example 17
Source File: Encodings.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
static void go(String enc, String str, final byte[] bytes, boolean bidir)
    throws Exception
{
    final Charset charset = Charset.forName(enc);

    /* String(byte[] bs, String enc) */
    if (!(new String(bytes, enc).equals(str)))
        throw new Exception(enc + ": String constructor failed");

    /* String(byte[] bs, Charset charset) */
    if (!(new String(bytes, charset).equals(str)))
        throw new Exception(charset + ": String constructor failed");

    /* String(byte[] bs, int off, int len, Charset charset) */
    String start = str.substring(0, 2);
    String end = str.substring(2);
    if (enc.equals("UTF-16BE") || enc.equals("UTF-16LE")) {
        if (!(new String(bytes, 0, 4, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 4, bytes.length - 4, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    } else if (enc.equals("UTF-16")) {
        if (!(new String(bytes, 0, 6, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
    } else {
        if (!(new String(bytes, 0, 2, charset).equals(start)))
            throw new Exception(charset + ": String constructor failed");
        if (!(new String(bytes, 2, bytes.length - 2, charset).equals(end)))
            throw new Exception(charset + ": String constructor failed");
    }

    /* InputStreamReader */
    ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    InputStreamReader r = new InputStreamReader(bi, enc);
    String inEnc = r.getEncoding();
    int n = str.length();
    char[] cs = new char[n];
    for (int i = 0; i < n;) {
        int m;
        if ((m = r.read(cs, i, n - i)) < 0)
            throw new Exception(enc + ": EOF on InputStreamReader");
        i += m;
    }
    if (!(new String(cs).equals(str)))
        throw new Exception(enc + ": InputStreamReader failed");

    if (!bidir) {
        System.err.println(enc + " --> " + inEnc);
        return;
    }

    /* String.getBytes(String enc) */
    byte[] bs = str.getBytes(enc);
    if (!equals(bs, bytes))
        throw new Exception(enc + ": String.getBytes failed");

    /* String.getBytes(Charset charset) */
    bs = str.getBytes(charset);
    if (!equals(bs, bytes))
        throw new Exception(charset + ": String.getBytes failed");

    // Calls to String.getBytes(Charset) shouldn't automatically
    // use the cached thread-local encoder.
    if (charset.name().equals("UTF-16BE")) {
        String s = new String(bytes, charset);
        // Replace the thread-local encoder with this one.
        byte[] bb = s.getBytes(Charset.forName("UTF-16LE"));
        if (bytes.length != bb.length) {
            // Incidental test.
            throw new RuntimeException("unequal length: "
                                       + bytes.length + " != "
                                       + bb.length);
        } else {
            boolean diff = false;
            // Expect different byte[] between UTF-16LE and UTF-16BE
            // even though encoder was previously cached by last call
            // to getBytes().
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] != bb[i])
                    diff = true;
            }
            if (!diff)
                throw new RuntimeException("byte arrays equal");
        }
    }

    /* OutputStreamWriter */
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(bo, enc);
    String outEnc = w.getEncoding();
    w.write(str);
    w.close();
    bs = bo.toByteArray();
    if (!equals(bs, bytes))
        throw new Exception(enc + ": OutputStreamWriter failed");

    System.err.println(enc + " --> " + inEnc + " / " + outEnc);
}
 
Example 18
Source File: CDWExporter.java    From synthea with Apache License 2.0 3 votes vote down vote up
/**
 * Helper method to write a line to a File.
 * Extracted to a separate method here to make it a little easier to replace implementations.
 *
 * @param line The line to write
 * @param writer The place to write it
 * @throws IOException if an I/O error occurs
 */
private static void write(String line, OutputStreamWriter writer) throws IOException {
  synchronized (writer) {
    writer.write(line);
    writer.flush();
  }
}
 
Example 19
Source File: IoUtil.java    From Vert.X-generator with MIT License 3 votes vote down vote up
/**
 * 将字符串存储为文件
 * 
 * @param dir
 *            目录
 * @param fileName
 *            文件名称
 * @param materi
 *            字符串内容
 * @param codeFormat
 *            字符编码方式
 * @throws Exception
 */
public static void StrToFile(Path dir, String fileName, String materi, String codeFormat) throws Exception {
	if (!isExists(dir)) {
		createDir(dir);
	}
	Path path = Paths.get(dir.toString(), fileName);
	OutputStream out = Files.newOutputStream(path, StandardOpenOption.CREATE);
	OutputStreamWriter writer = new OutputStreamWriter(out, codeFormat);
	writer.write(materi);
	writer.flush();
	out.close();
	writer.close();
}
 
Example 20
Source File: PropertyListParser.java    From Alite with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Saves a property list with the given object as root into a ASCII file.
 *
 * @param root The root object.
 * @param out  The output file.
 * @throws IOException When an error occurs during the writing process.
 */
public static void saveAsASCII(NSArray root, File out) throws IOException {
    OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(out), "ASCII");
    w.write(root.toASCIIPropertyList());
    w.close();
}