将获取的字符串转换为输入流,然后通过输出流写到文件上:
public static int appendFile(String text, OutputStream outStream) throws IOException { byte[] bs = text.getBytes("UTF-8"); InputStream in = new ByteArrayInputStream(bs); try { int byteCount = 0; byte[] buffer = new byte[1024]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); byteCount += bytesRead; } outStream.flush(); return byteCount; } finally { try { in.close(); } catch (IOException ex) { LOGGER.warn("Could not close InputStream", ex); } } }