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

The following examples show how to use java.io.OutputStreamWriter#append() . 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: GsonHttpMessageConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected void writeInternal(Object o, Type type, HttpOutputMessage outputMessage)
		throws IOException, HttpMessageNotWritableException {

	Charset charset = getCharset(outputMessage.getHeaders());
	OutputStreamWriter writer = new OutputStreamWriter(outputMessage.getBody(), charset);
	try {
		if (this.jsonPrefix != null) {
			writer.append(this.jsonPrefix);
		}
		if (type != null) {
			this.gson.toJson(o, type, writer);
		}
		else {
			this.gson.toJson(o, writer);
		}
		writer.close();
	}
	catch (JsonIOException ex) {
		throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
	}
}
 
Example 2
Source File: ShapeletFilter.java    From tsml with GNU General Public License v3.0 6 votes vote down vote up
protected void writeShapelets(ArrayList<Shapelet> kShapelets, OutputStreamWriter out){
    try {
        out.append("informationGain,seriesId,startPos,classVal,numChannels,dimension\n");
        for (Shapelet kShapelet : kShapelets) {
            out.append(kShapelet.qualityValue + "," + kShapelet.seriesId + "," + kShapelet.startPos + "," + kShapelet.classValue + "," + kShapelet.getNumDimensions() + "," + kShapelet.dimension+"\n");
            for (int i = 0; i < kShapelet.numDimensions; i++) {
                double[] shapeletContent = kShapelet.getContent().getShapeletContent(i);
                for (int j = 0; j < shapeletContent.length; j++) {
                    out.append(shapeletContent[j] + ",");
                }
                out.append("\n");
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ShapeletFilter.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 3
Source File: KuduSpanViewer.java    From incubator-retired-htrace with Apache License 2.0 6 votes vote down vote up
public static void appendJsonString(Span span, OutputStreamWriter writer) throws IOException {
  writer.append("{");
  appendField(JSON_FIELD_TRACE_ID, span.getSpanId().getLow(), writer);
  appendField(JSON_FIELD_SPAN_ID, span.getSpanId().getHigh(), writer);
  appendField(JSON_FIELD_DESCRIPTION, span.getDescription(), writer);
  if (span.getParents().length != 0) {
    appendField(JSON_FIELD_PARENT_ID, span.getParents()[0].getLow(), writer);
  }
  appendField(JSON_FIELD_START, span.getStartTimeMillis(), writer);
  appendField(JSON_FIELD_STOP, span.getStopTimeMillis(), writer);
  if (!span.getTimelineAnnotations().isEmpty()) {
    writer.append("\"");
    writer.append(JSON_FIELD_TIMELINE);
    writer.append("\"");
    writer.append(":");
    writer.append("[");
    for (TimelineAnnotation annotation : span.getTimelineAnnotations()) {
      writer.append("{");
      appendField(JSON_FIELD_TIMELINE_TIME, annotation.getTime(), writer);
      appendField(JSON_FIELD_TIMELINE_MESSEGE, annotation.getMessage(), writer);
      writer.append("}");
    }
    writer.append("]");
  }
  writer.append("}");
}
 
Example 4
Source File: NotesFragment.java    From ForPDA with GNU General Public License v3.0 6 votes vote down vote up
private void saveImageToExternalStorage(String json) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
    String date = new SimpleDateFormat("MMddyyy-HHmmss", Locale.getDefault()).format(new Date(System.currentTimeMillis()));
    String fileName = "ForPDA_Notes_" + date + ".json";
    File file = new File(root, fileName);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(json);

        myOutWriter.close();

        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getContext(), "Файл не сохранён: " + e.getMessage(), Toast.LENGTH_SHORT).show();
    }
    Toast.makeText(getContext(), "Заметки успешно экспортированы в " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
 
Example 5
Source File: HBaseSpanViewer.java    From incubator-retired-htrace with Apache License 2.0 6 votes vote down vote up
private static void appendFields(FieldDescriptor fd,
                                 Object value, 
                                 OutputStreamWriter writer) throws IOException {
  writer.append("\"");
  writer.append(fd.getName());
  writer.append("\"");
  writer.append(":");
  if (fd.isRepeated()) {
    writer.append("[");
    for (Iterator<?> it = ((List<?>) value).iterator(); it.hasNext();) {
      appendValue(fd, it.next(), writer);
      if (it.hasNext()) {
        writer.append(",");
      }
    }
    writer.append("]");
  } else {
    appendValue(fd, value, writer);
  }
}
 
Example 6
Source File: JavaIoFileSystemAccess.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void generateFile(String fileName, String outputConfigName, CharSequence contents) throws RuntimeIOException {
	File file = getFile(fileName, outputConfigName);
	if (!getOutputConfig(outputConfigName).isOverrideExistingResources() && file.exists()) {
		return;
	}
	try {
		createFolder(file.getParentFile());
		String encoding = getEncoding(getURI(fileName, outputConfigName));
		OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), encoding);
		try {
			writer.append(postProcess(fileName, outputConfigName, contents, encoding));
			if(callBack != null) 
				callBack.fileAdded(file);
			if (writeTrace)
				generateTrace(fileName, outputConfigName, contents);
		} finally {
			writer.close();
		}
	} catch (IOException e) {
		throw new RuntimeIOException(e);
	}
}
 
Example 7
Source File: DefaultMatcherTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void createAndCheckTextContent(String encoding) {
    FileObject root = FileUtil.createMemoryFileSystem().getRoot();
    try {
        OutputStream os = root.createAndOpen("file");
        try {
            OutputStreamWriter osw = new OutputStreamWriter(os,
                    encoding);
            try {
                osw.append("Test Text");
                osw.flush();
            } finally {
                osw.close();
            }
        } finally {
            os.close();
        }
        assertTrue("File with encoding " + encoding
                + " was detected as binary file",
                DefaultMatcher.hasTextContent(root.getFileObject("file")));
    } catch (UnsupportedEncodingException eee) {
        LOG.log(Level.INFO, "Unknown encoding {0}", encoding);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 8
Source File: KuduSpanViewer.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
private static void appendField(String field,
                                Object value,
                                OutputStreamWriter writer) throws IOException {
  writer.append("\"");
  writer.append(field);
  writer.append("\"");
  writer.append(":");
  appendStringValue(value.toString(), writer);
  writer.append(",");
}
 
Example 9
Source File: SettingsLoader.java    From comfortreader with GNU General Public License v3.0 5 votes vote down vote up
public Boolean addtoCurrentNotes(String note){

		String textwriteout = note;
		String path = getCurrentNotesFilePath();
		Boolean success = false;

		try {
			File myFile = new File(path);
			//if (!myFile.exists()) {
			//	myFile.mkdirs();
			//}
			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter =
					new OutputStreamWriter(fOut);
			myOutWriter.append(textwriteout);
			myOutWriter.close();
			fOut.close();
			success = true;

			//Toast.makeText(getBaseContext(),
			//		"Done writing out to 'Comfort Reader/notes" + filename + ".txt",
			//		Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
		//	Toast.makeText(getBaseContext(), e.getMessage(),
		//			Toast.LENGTH_SHORT).show();
		}


		return success;



		//wenn kein file am Path, dann neu anlegen
		//sonst Text einfach anhängen


	}
 
Example 10
Source File: Utils.java    From SmartPack-Kernel-Manager with GNU General Public License v3.0 5 votes vote down vote up
public static void create(String text, String path) {
    try {
        File logFile = new File(path);
        logFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(logFile);
        OutputStreamWriter myOutWriter =
                new OutputStreamWriter(fOut);
        myOutWriter.append(text);
        myOutWriter.close();
        fOut.close();
    } catch (Exception ignored) {
    }
}
 
Example 11
Source File: StreamEncoderOut.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "CharsetAndString")
public void test(Charset cs, Input input) throws IOException {
    OutputStreamWriter w = new OutputStreamWriter(DEV_NULL, cs);
    String t = generate(input.value, 8193);
    for (int i = 0; i < 10; i++) {
        w.append(t);
    }
}
 
Example 12
Source File: Util.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static void writeAll(OutputStream out, CharSequence content) throws IOException
{		
	OutputStreamWriter w = new OutputStreamWriter(out);
	try
	{
		w.append(content);
	}
	finally
	{
		w.flush();
	}
}
 
Example 13
Source File: Util.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static void writeToFile(com.sovworks.eds.fs.File dst, CharSequence content) throws IOException
{
	OutputStreamWriter w = new OutputStreamWriter(dst.getOutputStream());
	try
	{
		w.append(content);
	}
	finally
	{
		w.close();
	}
}
 
Example 14
Source File: HttpClientUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
public static String httpPostWithJSON(String postUrl, String json) {
        try {
            URL url = new URL(postUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(json);
            out.flush();
            out.close();
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();
            String result = IoConvertUtils.stream2String(is);
            return result;
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8"); // utf-8编码
//                // System.out.println(result);
//                return result;
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }
 
Example 15
Source File: FileResourcesUtil.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static boolean writeToFile(@NonNull String content, @Nullable String secretToEncode) {
    // Get the directory for the user's public pictures directory.
    final File path = new File(Environment.getExternalStorageDirectory(), "DHIS2");

    // Make sure the path directory exists.
    if (!path.exists()) {
        // Make it, if it doesn't exit
        path.mkdirs();
    }

    final File file = new File(path, "dhisDataBuckUp.txt");
    if (file.exists())
        file.delete();

    // Save your stream, don't forget to flush() it before closing it.

    try {
        boolean fileCreated = file.createNewFile();
        try (FileOutputStream fOut = new FileOutputStream(file)) {
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(content);

            myOutWriter.close();

            fOut.flush();
        }
        return fileCreated;
    } catch (IOException e) {
        Timber.e("File write failed: %s", e.toString());
        return false;
    }
}
 
Example 16
Source File: ManglingTest.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testMangledNames() throws Exception {
    File nidlFile = tempFolder.newFile("host_functions.nidl");
    // Generate empty C++ functions with corresponding NIDL file
    CxxFunctionGenerator sourceGen = new CxxFunctionGenerator();
    String cxxSource = sourceGen.generateCxx(NUM_FUNCTIONS, NUM_FUNCTION_PARAMS, nidlFile);

    // Parse binding from NIDL file
    ArrayList<Binding> bindings = NIDLParser.parseNIDLFile(nidlFile.getAbsolutePath());

    // Copy c++ function using the host g++ and extract the mangled symbol names.
    Process compiler = Runtime.getRuntime().exec("g++ -x c++ -S -o - -");
    OutputStreamWriter stdin = new OutputStreamWriter(compiler.getOutputStream());
    BufferedReader stdout = new BufferedReader(new InputStreamReader(compiler.getInputStream()));
    BufferedReader stderr = new BufferedReader(new InputStreamReader(compiler.getErrorStream()));
    stdin.append(cxxSource);
    stdin.close();
    int cxxReturnCode = compiler.waitFor();
    if (cxxReturnCode != 0) {
        stderr.lines().forEach(System.out::println);
        throw new Exception("g++ return code != 0");
    }
    sourceGen.extractMangledNames(stdout);

    // Check grCUDA-generated mangled names with compiler output
    int idx = 0;
    for (Binding binding : bindings) {
        String expectedMangledName = sourceGen.getMangledName(idx);
        String actualMangledName = binding.getSymbolName();
        assertEquals("incorrect mangling " + binding.toNIDLString(), expectedMangledName, actualMangledName);
        idx += 1;
    }
}
 
Example 17
Source File: HBaseSpanViewer.java    From incubator-retired-htrace with Apache License 2.0 5 votes vote down vote up
public static void appendJsonString(final Message message,
                                      OutputStreamWriter writer) throws IOException {
  writer.append("{");
  for (Iterator<Map.Entry<FieldDescriptor, Object>> iter =
         message.getAllFields().entrySet().iterator(); iter.hasNext();) {
    Map.Entry<FieldDescriptor, Object> field = iter.next();
    appendFields(field.getKey(), field.getValue(), writer);
    if (iter.hasNext()) {
      writer.append(",");
    }
  }
  writer.append("}");
}
 
Example 18
Source File: FileIODemo.java    From JavaCommon with Apache License 2.0 4 votes vote down vote up
public static void fileStream() {
	try {
		File f = new File("mkdirs/test/filetest.txt");
		FileOutputStream fop = new FileOutputStream(f);
		// 构建FileOutputStream对象,文件不存在会自动新建

		OutputStreamWriter writer = new OutputStreamWriter(fop, "gbk");
		// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk

		writer.append("中文输入");
		// 写入到缓冲区

		writer.append("\r\n");
		// 换行

		writer.append("English");
		// 刷新缓存冲,写入到文件,如果下面已经没有写入的内容了,直接close也会写入

		writer.close();
		// 关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉

		fop.close();
		// 关闭输出流,释放系统资源

		FileInputStream fip = new FileInputStream(f);
		// 构建FileInputStream对象

		InputStreamReader reader = new InputStreamReader(fip, "UTF-8");
		// 构建InputStreamReader对象,编码与写入相同

		StringBuffer sb = new StringBuffer();
		while (reader.ready()) {
			sb.append((char) reader.read());
			// 转成char加到StringBuffer对象中
		}
		System.out.println(sb.toString());
		reader.close();
		// 关闭读取流

		fip.close();
		// 关闭输入流,释放系统资源
	} catch (Exception e) {
	}
}
 
Example 19
Source File: ParserManagerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testParseDoesNotScheduleTasks () throws Exception {
    final CountDownLatch l = new CountDownLatch(1);
    MockServices.setServices (MockMimeLookup.class, TestEnvironmentFactory.class, MyScheduler.class);
    MockMimeLookup.setInstances (
        MimePath.get ("text/foo"), new FooParserFactory(),
                    new TaskFactory () {
            public Collection<SchedulerTask> create (Snapshot snapshot) {
                return Arrays.asList (new SchedulerTask[] {
                    new ParserResultTask() {
                        @Override
                        public void run(Result result, SchedulerEvent event) {
                            l.countDown();
                        }
                        @Override
                        public int getPriority() {
                            return 100;
                        }
                        @Override
                        public Class<? extends Scheduler> getSchedulerClass() {
                            return Scheduler.EDITOR_SENSITIVE_TASK_SCHEDULER;
                        }
                        @Override
                        public void cancel() {}
                    }
                });
            }
    });

    clearWorkDir ();
    //Collection c = MimeLookup.getLookup("text/boo").lookupAll (ParserFactory.class);
    FileObject workDir = FileUtil.toFileObject (getWorkDir ());
    FileObject testFile = FileUtil.createData (workDir, "bla.foo");
    FileUtil.setMIMEType ("foo", "text/foo");
    OutputStream outputStream = testFile.getOutputStream ();
    OutputStreamWriter writer = new OutputStreamWriter (outputStream);
    writer.append ("Toto je testovaci file, na kterem se budou delat hnusne pokusy!!!");
    writer.close ();
    Source source = Source.create (testFile);

    ParserManager.parse (Collections.singleton(source), new UserTask () {
        @Override
        public void run(ResultIterator resultIterator) throws Exception {
        }
    });

    DataObject.find(testFile).getLookup().lookup(EditorCookie.class).openDocument();

    assertFalse("Should not schedule the task", l.await(2, TimeUnit.SECONDS));
}
 
Example 20
Source File: MainActivity.java    From goprohero with MIT License 4 votes vote down vote up
public void startGPSLog(View view){
        gps = new GPStracker(MainActivity.this);
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy--HH-mm-ss");
        //get current date time with Date()
        Date date = new Date();
        String thedate = dateFormat.format(date);
        DateFormat dateFormatTwo = new SimpleDateFormat("dd-MM-yyyy");
        //get current date time with Date()
        Date dateTwo = new Date();
        String theotherdate = dateFormatTwo.format(dateTwo);
        String thisfiledate = dateFormatTwo.format(dateTwo);
        // check if GPS enabled
        if(gps.canGetLocation()){

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "GPS Tracking started", Toast.LENGTH_LONG).show();
            try {
                File myFile = new File("/sdcard/GoProGPSTrack" + theotherdate + ".txt");
                myFile.createNewFile();
                FileOutputStream fOut = new FileOutputStream(myFile);
                OutputStreamWriter myOutWriter =
                        new OutputStreamWriter(fOut);
                myOutWriter.append("<gpx>");
                myOutWriter.append("<trk>");
                myOutWriter.append("<name>GoPro Track</name>");
                myOutWriter.append("<trkseg>");
                myOutWriter.append("<latitude>" + latitude + "</latitude>");
                myOutWriter.append("<longitude>" + longitude + "</longitude>");
                myOutWriter.append("<time>" + date + "</time>");
                myOutWriter.append("</trkseg>");
                myOutWriter.close();
                fOut.close();
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }else{
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }

}