下面列出了java.nio.channels.OverlappingFileLockException#java.io.OutputStreamWriter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Called by CodeModel to store the specified file.
* The callee must allocate a storage to store the specified file.
*
* <p>
* The returned stream will be closed before the next file is
* stored. So the callee can assume that only one OutputStream
* is active at any given time.
*
* @param pkg
* The package of the file to be written.
* @param fileName
* File name without the path. Something like
* "Foo.java" or "Bar.properties"
*/
public Writer openSource( JPackage pkg, String fileName ) throws IOException {
final OutputStreamWriter bw = encoding != null
? new OutputStreamWriter(openBinary(pkg,fileName), encoding)
: new OutputStreamWriter(openBinary(pkg,fileName));
// create writer
try {
return new UnicodeEscapeWriter(bw) {
// can't change this signature to Encoder because
// we can't have Encoder in method signature
private final CharsetEncoder encoder = EncoderFactory.createEncoder(bw.getEncoding());
@Override
protected boolean requireEscaping(int ch) {
// control characters
if( ch<0x20 && " \t\r\n".indexOf(ch)==-1 ) return true;
// check ASCII chars, for better performance
if( ch<0x80 ) return false;
return !encoder.canEncode((char)ch);
}
};
} catch( Throwable t ) {
return new UnicodeEscapeWriter(bw);
}
}
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);
}
}
@Override
public void run() {
while (true) {
try {
Socket connectionSocket = this.serverSocket.accept();
if (this.capacity <= this.connections.get()) {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(connectionSocket.getOutputStream()));
pw.println("// Maximum server capacity is reached (" + this.capacity + ").");
pw.flush();
LOG.error("Maximum server capacity is reached (" + this.capacity + ").");
connectionSocket.close();
continue;
}
this.connections.incrementAndGet();
InteractiveProcessor processor = new InteractiveProcessor(this, connectionSocket, null, connectionSocket.getInputStream(), connectionSocket.getOutputStream());
} catch (IOException ioe) {
}
}
}
@Test
public void writesToByteArray() {
final String content = "Hello, товарищ! How are you?";
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
new Assertion<>(
"Can't copy Input to Writer",
new TeeInput(
new InputOf(content),
new OutputTo(
new WriterAsOutputStream(
new OutputStreamWriter(
baos, StandardCharsets.UTF_8
),
StandardCharsets.UTF_8,
// @checkstyle MagicNumber (1 line)
13
)
)
),
new InputHasContent(
new TextOf(baos::toByteArray, StandardCharsets.UTF_8)
)
).affirm();
}
protected void createExportFile(ColumnGenerator... extraCols)
throws IOException {
String ext = ".txt";
Path tablePath = getTablePath();
Path filePath = new Path(tablePath, "part0" + ext);
Configuration conf = new Configuration();
if (!BaseSqoopTestCase.isOnPhysicalCluster()) {
conf.set(CommonArgs.FS_DEFAULT_NAME, CommonArgs.LOCAL_FS);
}
FileSystem fs = FileSystem.get(conf);
fs.mkdirs(tablePath);
OutputStream os = fs.create(filePath);
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os));
for (int i = 0; i < 3; i++) {
String line = getRecordLine(i, extraCols);
w.write(line);
LOG.debug("Create Export file - Writing line : " + line);
}
w.close();
os.close();
}
public static void writeFile(List<BigInteger> elements, FileSystem fs, Path path, boolean deleteOnExit)
{
try
{
// create writer
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fs.create(path, true)));
// write each element on a new line
for (BigInteger element : elements)
{
bw.write(element.toString());
bw.newLine();
}
bw.close();
// delete file once the filesystem is closed
if (deleteOnExit)
{
fs.deleteOnExit(path);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
@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);
}
@Override
public void processView(ViewEngineContext context) throws ViewEngineException {
Map<String, Object> model = new HashMap<>(context.getModels().asMap());
model.put("request", context.getRequest(HttpServletRequest.class));
Charset charset = resolveCharsetAndSetContentType(context);
try (Writer writer = new OutputStreamWriter(context.getOutputStream(), charset);
InputStream resourceAsStream = servletContext.getResourceAsStream(resolveView(context));
InputStreamReader in = new InputStreamReader(resourceAsStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(in);) {
String viewContent = bufferedReader.lines().collect(Collectors.joining());
Template template = handlebars.compileInline(viewContent);
template.apply(model, writer);
} catch (IOException e) {
throw new ViewEngineException(e);
}
}
/**
* Save a payload to the log file
* @param frame
* @param log
* @throws IOException
*/
protected void save(Frame frame, String log) throws IOException {
if (!Config.logFileDirectory.equalsIgnoreCase("")) {
log = Config.logFileDirectory + File.separator + log;
}
synchronized(this) { // make sure we have exlusive access to the file on disk, otherwise a removed frame can clash with this
File aFile = new File(log );
if(!aFile.exists()){
aFile.createNewFile();
}
//Log.println("Saving: " + log);
//use buffering and append to the existing file
FileOutputStream dis = new FileOutputStream(log, true);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(dis));
try {
frame.save(writer);
} finally {
writer.flush();
writer.close();
}
writer.close();
dis.close();
}
}
@Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
T wireFeed = newFeed();
buildFeedMetadata(model, wireFeed, request);
buildFeedEntries(model, wireFeed, request, response);
setResponseContentType(request, response);
if (!StringUtils.hasText(wireFeed.getEncoding())) {
wireFeed.setEncoding("UTF-8");
}
WireFeedOutput feedOutput = new WireFeedOutput();
ServletOutputStream out = response.getOutputStream();
feedOutput.output(wireFeed, new OutputStreamWriter(out, wireFeed.getEncoding()));
out.flush();
}
private String streamToString(InputStream in) throws IOException, PyServeException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStreamWriter out = new OutputStreamWriter(bout);
InputStreamReader input = new InputStreamReader(in);
char[] buffer = new char[8192];
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
out.write(buffer, 0, n);
count += n;
}
if (count > MAX_SCRIPT_SIZE) {
throw new PyServeException("Exceed the max script size limit (8M).");
}
out.flush();
return bout.toString();
}
public void writeTo(DiskLruCache.Editor editor) throws IOException {
OutputStream out = editor.newOutputStream(ENTRY_METADATA);
Writer writer = new BufferedWriter(new OutputStreamWriter(out, UTF_8));
writer.write(uri + '\n');
writer.write(requestMethod + '\n');
writer.write(Integer.toString(varyHeaders.length()) + '\n');
for (int i = 0; i < varyHeaders.length(); i++) {
writer.write(varyHeaders.getFieldName(i) + ": " + varyHeaders.getValue(i) + '\n');
}
writer.write(responseHeaders.getStatusLine() + '\n');
writer.write(Integer.toString(responseHeaders.length()) + '\n');
for (int i = 0; i < responseHeaders.length(); i++) {
writer.write(responseHeaders.getFieldName(i) + ": " + responseHeaders.getValue(i) + '\n');
}
if (isHttps()) {
writer.write('\n');
writer.write(cipherSuite + '\n');
writeCertArray(writer, peerCertificates);
writeCertArray(writer, localCertificates);
}
writer.close();
}
public void fixHeader() {
if (header == null) return;
try {
List<String> content = Lists.newArrayList(header);
content.addAll(readAllLines());
file.delete();
file.createNewFile();
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
for (String line : content) {
buf.write(line + System.getProperty("line.separator"));
}
buf.close();
} catch (Exception ex) {
Shared.errorManager.criticalError("Failed to modify file " + file, ex);
}
}
/**
* Calls the LoLA service with the given PNML under the given URL.
* @param pnml of the Petri net
* @param address - URL of the LoLA service
* @return text response from LoLA
* @throws IOException
*/
private static String callLola(String pnml, String address) throws IOException {
URL url = new URL(address);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setReadTimeout(TIMEOUT);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
// send pnml
writer.write("input=" + URLEncoder.encode(pnml, "UTF-8"));
writer.flush();
// get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
return answer.toString();
}
static void redirectSystemIn() throws Exception {
// This starts the MvsConsole listener if it's not already started (by the JZOS Batch Launcher)
if (!MvsConsole.isListening()) {
MvsConsole.startMvsCommandListener();
}
PipedOutputStream pos = new PipedOutputStream();
final Writer writer = new OutputStreamWriter(pos); // use default file.encoding
MvsConsole.registerMvsCommandCallback(
new MvsCommandCallback() {
public void handleStart(String parms) {};
public void handleModify(String cmd) {
try {
writer.write(cmd + "\n");
writer.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public boolean handleStop() { return true; } // System.exit()
});
PipedInputStream pis = new PipedInputStream(pos);
System.setIn(pis);
}
@Override protected void performRewrite(TransformationContext ctx) {
try {
FileObject resource = ctx.getWorkingCopy().getFileObject().getParent().getFileObject("test.txt");
Assert.assertNotNull(resource);
Reader r = new InputStreamReader(ctx.getResourceContent(resource), "UTF-8");
ByteArrayOutputStream outData = new ByteArrayOutputStream();
Writer w = new OutputStreamWriter(outData, "UTF-8");
int read;
while ((read = r.read()) != -1) {
if (read != '\n') read++;
w.write(read);
}
r.close();
w.close();
OutputStream out = ctx.getResourceOutput(resource);
out.write(outData.toByteArray());
out.close();
} catch (Exception ex) {
throw new IllegalStateException(ex);
}
}
@VisibleForTesting
static Path generateVersionIndex(String groupId, String artifactId, List<String> versions)
throws IOException, TemplateException, URISyntaxException {
Path directory = outputDirectory(groupId, artifactId, "snapshot").getParent();
directory.toFile().mkdirs();
Path page = directory.resolve("index.html");
Map<String, Object> templateData = new HashMap<>();
templateData.put("versions", versions);
templateData.put("groupId", groupId);
templateData.put("artifactId", artifactId);
File dashboardFile = page.toFile();
try (Writer out =
new OutputStreamWriter(new FileOutputStream(dashboardFile), StandardCharsets.UTF_8)) {
Template dashboard = freemarkerConfiguration.getTemplate("/templates/version_index.ftl");
dashboard.process(templateData, out);
}
copyResource(directory, "css/dashboard.css");
return page;
}
@Override
public void compose(Element e, OutputStream stream, OutputStyle style, String identity) throws FHIRException, IOException {
OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
if (style == OutputStyle.CANONICAL)
json = new JsonCreatorCanonical(osw);
else
json = new JsonCreatorGson(osw);
json.setIndent(style == OutputStyle.PRETTY ? " " : "");
json.beginObject();
prop("resourceType", e.getType(), null);
Set<String> done = new HashSet<String>();
for (Element child : e.getChildren()) {
compose(e.getName(), e, done, child);
}
json.endObject();
json.finish();
osw.flush();
}
private FileObject createItemFileWithInLineDescription() throws Exception {
FileObject fo = itemsFolder.createData(ITEM_FILE);
FileLock lock = fo.lock();
try {
OutputStreamWriter writer = new OutputStreamWriter(fo.getOutputStream(lock), "UTF-8");
try {
writer.write("<?xml version='1.0' encoding='UTF-8'?>");
writer.write("<!DOCTYPE editor_palette_item PUBLIC '-//NetBeans//Editor Palette Item 1.1//EN' 'http://www.netbeans.org/dtds/editor-palette-item-1_1.dtd'>");
writer.write("<editor_palette_item version='1.1'>");
writer.write("<body><![CDATA[" + BODY + "]]></body>");
writer.write("<icon16 urlvalue='" + ICON16 + "' />");
writer.write("<icon32 urlvalue='" + ICON32 + "' />");
writer.write("<inline-description> <display-name>"
+NbBundle.getBundle(BUNDLE_NAME).getString(NAME_KEY)+"</display-name> <tooltip>"
+NbBundle.getBundle(BUNDLE_NAME).getString(TOOLTIP_KEY)+"</tooltip> </inline-description>");
writer.write("</editor_palette_item>");
} finally {
writer.close();
}
} finally {
lock.releaseLock();
}
return fo;
}
public static @NotNull SentryEnvelopeItem fromSession(
final @NotNull ISerializer serializer, final @NotNull Session session) throws IOException {
Objects.requireNonNull(serializer, "ISerializer is required.");
Objects.requireNonNull(session, "Session is required.");
final CachedItem cachedItem =
new CachedItem(
() -> {
try (final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) {
serializer.serialize(session, writer);
return stream.toByteArray();
}
});
SentryEnvelopeItemHeader itemHeader =
new SentryEnvelopeItemHeader(
SentryItemType.Session, () -> cachedItem.getBytes().length, "application/json", null);
return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes());
}
private void writeSourceFile() throws Exception {
File f = new File(getWorkDir(), "source.fxml");
FileObject dirFo = FileUtil.toFileObject(getWorkDir());
OutputStream ostm = dirFo.createAndOpen("source.fxml");
OutputStreamWriter wr = new OutputStreamWriter(ostm);
wr.write(text);
wr.flush();
wr.close();
sourceFO = dirFo.getFileObject("source.fxml");
}
/**
* Open an writer for the file, using the encoding (if any) given in the
* doclet configuration.
* The file must have been created with a location of
* {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
*/
public Writer openWriter() throws IOException, UnsupportedEncodingException {
if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
throw new IllegalStateException();
createDirectoryForFile(file);
FileOutputStream fos = new FileOutputStream(file);
if (configuration.docencoding == null) {
return new BufferedWriter(new OutputStreamWriter(fos));
} else {
return new BufferedWriter(new OutputStreamWriter(fos, configuration.docencoding));
}
}
public CsvWriter(OutputStream outputStream, CodecDefinition definition) {
super(definition);
try {
OutputStreamWriter buffer = new OutputStreamWriter(outputStream, StringUtility.CHARSET);
this.outputStream = new CSVPrinter(buffer, FORMAT);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
}
/**
* 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);
}
}
public static void main(String[] args) throws IOException {
File in = new File("R.txt");
File out = new File("public.xml");
if (!in.exists()) {
throw new NullPointerException("R.txt is not null.");
}
try {
out.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return;
}
System.out.println(in.getAbsolutePath());
System.out.println(out.getAbsolutePath());
InputStreamReader read = new InputStreamReader(new FileInputStream(in));
BufferedReader bufferedReader = new BufferedReader(read);
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(out));
BufferedWriter bufferedWriter = new BufferedWriter(writer);
Map<String, PublicLine> xml = new HashMap<>();
buildXml(bufferedReader, xml);
List<PublicLine> lines = new ArrayList<>();
lines.addAll(xml.values());
Collections.sort(lines);
saveFile(lines, bufferedWriter);
close(bufferedReader);
close(bufferedWriter);
System.out.println("End.");
}
/**
* Writes model information in the Apple EOModelBundle format.
*
* For document structure and definition see: http://developer.apple.com/documentation/InternetWeb/Reference/WO_BundleReference/Articles/EOModelBundle.html
*
* @param eoModelMap
* @param eomodeldFullPath
* @param filename
* @throws FileNotFoundException
* @throws UnsupportedEncodingException
*/
public static void writePlistFile(Map<String, Object> eoModelMap, String eomodeldFullPath, String filename, boolean useXml) throws FileNotFoundException, UnsupportedEncodingException {
try (PrintWriter plistWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(eomodeldFullPath, filename)), "UTF-8")))) {
if (useXml) {
plistWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
plistWriter.println("<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
plistWriter.println("<plist version=\"1.0\">");
writePlistPropertyMapXml(eoModelMap, 0, plistWriter);
plistWriter.println("</plist>");
} else {
writePlistPropertyMap(eoModelMap, 0, plistWriter, false);
}
}
}
public static void writeHttpContent(String content) {
try {
System.out.println(content);
pw = new PrintWriter(new OutputStreamWriter(uc.getOutputStream()), true);
pw.print(content);
pw.flush();
pw.close();
br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String httpResp = br.readLine();
Map<String, List<String>> headerFields = uc.getHeaderFields();
if (headerFields.containsKey("Set-Cookie")) {
List<String> header = headerFields.get("Set-Cookie");
for (int i = 0; i < header.size(); i++) {
String tmp = header.get(i);
if (tmp.contains("skey")) {
skeycookie = tmp;
}
if (tmp.contains("user")) {
usercookie = tmp;
}
}
} else {
System.out.println("shit");
}
System.out.println();
skeycookie = skeycookie.substring(0, skeycookie.indexOf(";"));
System.out.println(skeycookie);
if (!usercookie.contains("user")) {
login = false;
} else {
login = true;
usercookie = usercookie.substring(0, usercookie.indexOf(";"));
System.out.println(usercookie);
}
} catch (Exception e) {
//System.out.println("ex " + e.toString());
}
}
public static String generateJson(Service service) throws IOException {
File serviceSpecFile = File.createTempFile(service.getName(), ".json");
String buffer = jsonSerDeser.toJson(service);
Writer w = new OutputStreamWriter(new FileOutputStream(serviceSpecFile),
StandardCharsets.UTF_8);
try (PrintWriter pw = new PrintWriter(w)) {
pw.append(buffer);
}
return serviceSpecFile.getAbsolutePath();
}
@Override
protected void handleSend(HttpURLConnection hconn) throws IOException {
OutputStreamWriter wr = new OutputStreamWriter(hconn.getOutputStream());
CommandTarget cmd = (CommandTarget) command;
StringBuilder data = new StringBuilder();
data.append("instanceName=").append(cmd.target);
wr.write(data.toString());
wr.flush();
wr.close();
}
/**
* We explicitly need to write ASCII files because that is what C
* compilers understand.
*/
protected PrintWriter wrapWriter(OutputStream o) throws Util.Exit {
try {
return new PrintWriter(new OutputStreamWriter(o, "ISO8859_1"), true);
} catch (UnsupportedEncodingException use) {
util.bug("encoding.iso8859_1.not.found");
return null; /* dead code */
}
}