Java Code Examples for java.io.Writer.close()

The following are Jave code examples for showing how to use close() of the java.io.Writer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: hadoop   File: TestCombineTextInputFormat.java   Source Code and License Vote up 6 votes
private static void createFiles(int length, int numFiles, Random random)
  throws IOException {
  Range[] ranges = createRanges(length, numFiles, random);

  for (int i = 0; i < numFiles; i++) {
    Path file = new Path(workDir, "test_" + i + ".txt");
    Writer writer = new OutputStreamWriter(localFs.create(file));
    Range range = ranges[i];
    try {
      for (int j = range.start; j < range.end; j++) {
        writer.write(Integer.toString(j));
        writer.write("\n");
      }
    } finally {
      writer.close();
    }
  }
}
 
Example 2
Project: Cubes_2   File: Settings.java   Source Code and License Vote up 6 votes
public static boolean write() {
	FileHandle fileHandle = Compatibility.get().getBaseFolder().child("settings.json");
	JsonObject json = new JsonObject();
	for (Map.Entry<String, Setting> entry : settings.entrySet()) {
		json.set(entry.getKey(), entry.getValue().toJson());
	}
	try {
		Writer writer = fileHandle.writer(false);
		json.writeTo(writer, WriterConfig.PRETTY_PRINT);
		writer.close();
	} catch (Exception e) {
		Log.error("Failed to write settings", e);
		fileHandle.delete();
		return false;
	}
	return true;
}
 
Example 3
Project: guava-mock   File: AppendableWriterTest.java   Source Code and License Vote up 6 votes
public void testCloseFlush() throws IOException {
  SpyAppendable spy = new SpyAppendable();
  Writer writer = new AppendableWriter(spy);

  writer.write("Hello");
  assertFalse(spy.flushed);
  assertFalse(spy.closed);

  writer.flush();
  assertTrue(spy.flushed);
  assertFalse(spy.closed);

  writer.close();
  assertTrue(spy.flushed);
  assertTrue(spy.closed);
}
 
Example 4
Project: openjdk-jdk10   File: T7159016.java   Source Code and License Vote up 6 votes
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver() || written++ > 0) {
        return false;
    }
    messager.printMessage(Diagnostic.Kind.NOTE, "writing Generated.java");
    try {
        Writer w = processingEnv.getFiler().createSourceFile("p.Generated").openWriter();
        try {
            w.write("package p; public class Generated { public static void m() { } }");
        } finally {
            w.close();
        }
    } catch (IOException x) {
        messager.printMessage(Diagnostic.Kind.ERROR, x.toString());
    }
    return true;
}
 
Example 5
Project: hadoop-oss   File: TestJarFinder.java   Source Code and License Vote up 6 votes
@Test
public void testNoManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testNoManifest");
  delete(dir);
  dir.mkdirs();
  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
 
Example 6
Project: openjdk-jdk10   File: T7159016.java   Source Code and License Vote up 6 votes
public static void main(String[] args) throws Exception {
    File src = new File("C.java");
    Writer w = new FileWriter(src);
    try {
        w.write("import static p.Generated.m;\nclass C { {m(); } }\n");
        w.flush();
    } finally {
        w.close();
    }
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null)) {
        JavaCompiler.CompilationTask task = jc.getTask(null, fm, null, null, null,
                                                       fm.getJavaFileObjects(src));
        task.setProcessors(Collections.singleton(new Proc()));
        if (!task.call()) {
            throw new Error("Test failed");
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: SerialDataConvertor.java   Source Code and License Vote up 6 votes
/** store the setting object even if was not changed */
private void writeDown() throws IOException {
    Object inst = instance.get();
    if (inst == null) return ;
    
    ByteArrayOutputStream b = new ByteArrayOutputStream(1024);
    Writer w = new OutputStreamWriter(b, "UTF-8"); // NOI18N
    try {
        isWriting = true;
        Convertor conv = getConvertor();
        if (conv != null) {
            conv.write(w, inst);
        } else {
            write(w, inst);
        }
    } finally {
        w.close();
        isWriting = false;
    }
    isChanged = false;

    buf = b;
    file.getFileSystem().runAtomicAction(this);
    buf = null;
    if (!isChanged) firePropertyChange(PROP_SAVE);
}
 
Example 8
Project: Reer   File: DefaultMavenPom.java   Source Code and License Vote up 5 votes
private void writeNonEffectivePom(final Writer pomWriter) throws IOException {
    try {
        withXmlActions.transform(pomWriter, POM_FILE_ENCODING, new ErroringAction<Writer>() {
            protected void doExecute(Writer writer) throws IOException {
                new MavenXpp3Writer().write(writer, getModel());
            }
        });
    } finally {
        pomWriter.close();
    }
}
 
Example 9
Project: hadoop-oss   File: TestJarFinder.java   Source Code and License Vote up 5 votes
@Test
public void testExistingManifest() throws Exception {
  File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
                      TestJarFinder.class.getName() + "-testExistingManifest");
  delete(dir);
  dir.mkdirs();

  File metaInfDir = new File(dir, "META-INF");
  metaInfDir.mkdirs();
  File manifestFile = new File(metaInfDir, "MANIFEST.MF");
  Manifest manifest = new Manifest();
  OutputStream os = new FileOutputStream(manifestFile);
  manifest.write(os);
  os.close();

  File propsFile = new File(dir, "props.properties");
  Writer writer = new FileWriter(propsFile);
  new Properties().store(writer, "");
  writer.close();
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  JarOutputStream zos = new JarOutputStream(baos);
  JarFinder.jarDir(dir, "", zos);
  JarInputStream jis =
    new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
  Assert.assertNotNull(jis.getManifest());
  jis.close();
}
 
Example 10
Project: hadoop   File: AuthenticatorTestCase.java   Source Code and License Vote up 5 votes
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    URL url = new URL(getBaseURL());
    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    Assert.assertFalse(token.isSet());
    TestConnectionConfigurator connConf = new TestConnectionConfigurator();
    AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
    HttpURLConnection conn = aUrl.openConnection(url, token);
    Assert.assertTrue(connConf.invoked);
    String tokenStr = token.toString();
    if (doPost) {
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
    }
    conn.connect();
    if (doPost) {
      Writer writer = new OutputStreamWriter(conn.getOutputStream());
      writer.write(POST);
      writer.close();
    }
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    if (doPost) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String echo = reader.readLine();
      Assert.assertEquals(POST, echo);
      Assert.assertNull(reader.readLine());
    }
    aUrl = new AuthenticatedURL();
    conn = aUrl.openConnection(url, token);
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    Assert.assertEquals(tokenStr, token.toString());
  } finally {
    stop();
  }
}
 
Example 11
Project: joai-project   File: Harvester.java   Source Code and License Vote up 5 votes
/**
 *  Writes the given element's subtree to the specified file.
 *
 * @param  fname           The output file name
 * @param  ele             The xml Element subtree to write to file
 * @param  doc             The Document
 * @return                 True if content previously existed in the given file and the content is the same
 *      as the new content provided
 * @exception  Hexception  If exception
 */
private boolean writedoc(
		String fname,
		Element ele,
		Document doc)
		 throws Hexception {
	try {
		boolean contentEquals = false;

		String s1 = null;
		File f = new File(fname);
		if (f.exists())
			s1 = Files.readFileToEncoding(f, "UTF-8").toString();

		FileOutputStream fos = new FileOutputStream(f);
		OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
		Writer wtr = new BufferedWriter(osw);
		OutputFormat format = new OutputFormat(doc, "UTF-8", true);
		// Indenting true
		format.setMethod("xml");
		// May not ne necessary to call this
		format.setLineWidth(0);
		// No line wrapping
		XMLSerializer ser = new XMLSerializer(wtr, format);
		ser.serialize(ele);
		fos.close();
		osw.close();
		wtr.close();

		if (s1 != null)
			contentEquals = s1.contentEquals(Files.readFileToEncoding(f, "UTF-8"));

		return contentEquals;
	} catch (IOException ioe) {
		throw new Hexception("cannot write file \"" + fname
				 + "\"  reason: " + ioe);
	}
}
 
Example 12
Project: incubator-netbeans   File: HintsTestBase.java   Source Code and License Vote up 5 votes
protected void performTestDoNotPerform(String className, int line, int column) throws Exception {
    prepareTest(className);
    DataObject od = DataObject.find(testSource);
    EditorCookie ec = od.getCookie(EditorCookie.class);
    
    Document doc = ec.openDocument();
    
    List<ErrorDescription> errors = new ErrorHintsProvider().computeErrors(info, doc, Utilities.JAVA_MIME_TYPE);
    List<Fix> fixes = new ArrayList<Fix>();
    
    for (ErrorDescription d : errors) {
        if (getStartLine(d) + 1 == line)
            fixes.addAll(getFixes(d));
    }
    
    fixes = sortFixes(fixes);
    
    File fixesDump = new File(getWorkDir(), getName() + "-hints.out");
    File diff   = new File(getWorkDir(), getName() + "-hints.diff");
    
    Writer hintsWriter = new FileWriter(fixesDump);
    
    for (Fix f : fixes) {
        hintsWriter.write(f.getText());
        hintsWriter.write("\n");
    }
    
    hintsWriter.close();
    
    File hintsGolden = getGoldenFile(getName() + "-hints.pass");
    
    assertFile(fixesDump, hintsGolden, diff);
}
 
Example 13
Project: hadoop   File: TestFileInputFormatPathFilter.java   Source Code and License Vote up 5 votes
protected Path createFile(String fileName) throws IOException {
  Path file = new Path(workDir, fileName);
  Writer writer = new OutputStreamWriter(localFs.create(file));
  writer.write("");
  writer.close();
  return localFs.makeQualified(file);
}
 
Example 14
Project: sql-first-mapper   File: DaoWriter.java   Source Code and License Vote up 5 votes
/**
 * Write <query>.sql to resources folder
 *
 * @param queryDesc information on query
 */
private void writeResource(QueryDesc queryDesc) {
    Filer filer = processingEnv.getFiler();
    try {
        FileObject o = filer.createResource(StandardLocation.CLASS_OUTPUT,
                queryDesc.getPackageName() + ".sql", queryDesc.getMethodNameFirstUpper() + ".sql");
        Writer w = o.openWriter();
        w.append(queryDesc.getQuery());
        w.flush();
        w.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Project: hadoop   File: TestLdapGroupsMapping.java   Source Code and License Vote up 5 votes
@Test
public void testExtractPassword() throws IOException {
  File testDir = new File(System.getProperty("test.build.data", 
                                             "target/test-dir"));
  testDir.mkdirs();
  File secretFile = new File(testDir, "secret.txt");
  Writer writer = new FileWriter(secretFile);
  writer.write("hadoop");
  writer.close();
  
  LdapGroupsMapping mapping = new LdapGroupsMapping();
  Assert.assertEquals("hadoop",
      mapping.extractPassword(secretFile.getPath()));
}
 
Example 16
Project: hadoop   File: TestServer.java   Source Code and License Vote up 5 votes
@Test
@TestDir
public void loadingSiteConfig() throws Exception {
  String dir = TestDirHelper.getTestDir().getAbsolutePath();
  File configFile = new File(dir, "testserver-site.xml");
  Writer w = new FileWriter(configFile);
  w.write("<configuration><property><name>testserver.a</name><value>site</value></property></configuration>");
  w.close();
  Server server = new Server("testserver", dir, dir, dir, dir);
  server.init();
  assertEquals(server.getConfig().get("testserver.a"), "site");
}
 
Example 17
Project: tomcat7   File: WebdavServlet.java   Source Code and License Vote up 4 votes
/**
 * Send a multistatus element containing a complete error report to the
 * client.
 *
 * @param req Servlet request
 * @param resp Servlet response
 * @param errorList List of error to be displayed
 */
private void sendReport(HttpServletRequest req, HttpServletResponse resp,
                        Hashtable<String,Integer> errorList)
        throws IOException {

    resp.setStatus(WebdavStatus.SC_MULTI_STATUS);

    String absoluteUri = req.getRequestURI();
    String relativePath = getRelativePath(req);

    XMLWriter generatedXML = new XMLWriter();
    generatedXML.writeXMLHeader();

    generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus",
            XMLWriter.OPENING);

    Enumeration<String> pathList = errorList.keys();
    while (pathList.hasMoreElements()) {

        String errorPath = pathList.nextElement();
        int errorCode = errorList.get(errorPath).intValue();

        generatedXML.writeElement("D", "response", XMLWriter.OPENING);

        generatedXML.writeElement("D", "href", XMLWriter.OPENING);
        String toAppend = errorPath.substring(relativePath.length());
        if (!toAppend.startsWith("/"))
            toAppend = "/" + toAppend;
        generatedXML.writeText(absoluteUri + toAppend);
        generatedXML.writeElement("D", "href", XMLWriter.CLOSING);
        generatedXML.writeElement("D", "status", XMLWriter.OPENING);
        generatedXML.writeText("HTTP/1.1 " + errorCode + " "
                + WebdavStatus.getStatusText(errorCode));
        generatedXML.writeElement("D", "status", XMLWriter.CLOSING);

        generatedXML.writeElement("D", "response", XMLWriter.CLOSING);

    }

    generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING);

    Writer writer = resp.getWriter();
    writer.write(generatedXML.toString());
    writer.close();

}
 
Example 18
Project: dacapobench   File: NumGuess.java   Source Code and License Vote up 4 votes
/**
 * @see org.dacapo.tomcat.HttpGet#fetch(org.dacapo.tomcat.Session,
 * java.io.File, boolean)
 */
@Override
public boolean fetch(Session session, File logFile, boolean keep) throws IOException {
  Writer output = new FileWriter(logFile);
  try {
    int guess = 64;
    int stride = 32;
    for (int i = 0; i < 10; i++) {
      /*
       * First query uses no parameters - subsequent ones pass the initial
       * guess
       */
      GetMethod get = new GetMethod(formatUrl(session, address + (i == 0 ? "" : "?guess=" + guess)));
      final int iGetResultCode = session.httpClient.executeMethod(get);
      final String responseBody = readStream(get.getResponseBodyAsStream());
      if (keep)
        output.write(responseBody);
      if (iGetResultCode != expectedStatus) {
        System.err.printf("URL %s returned status %d (expected %d)%n", address, iGetResultCode, expectedStatus);
        if (!keep)
          output.write(responseBody);
        return false;
      }

      /*
       * Analyse the response and decide what to do next
       */
      if (responseBody.contains("Congratulations!  You got it.")) {
        return true;
      } else if (responseBody.contains("Welcome to the Number Guess game.")) {
        // First page
      } else if (responseBody.contains("Good guess, but nope.  Try <b>higher</b>.")) {
        guess += stride;
        stride /= 2;
      } else if (responseBody.contains("Good guess, but nope.  Try <b>lower</b>.")) {
        guess -= stride;
        stride /= 2;
      } else {
        if (!keep)
          output.write(responseBody);
        output.write("Unexpected result - quitting\n");
        return false;
      }
    }
    output.write("Too many iterations - exiting\n");
    return false;
  } finally {
    output.close();
  }
}
 
Example 19
Project: hadoop   File: TestTextInputFormat.java   Source Code and License Vote up 4 votes
@Test (timeout=500000)
public void testFormat() throws Exception {
  JobConf job = new JobConf(defaultConf);
  Path file = new Path(workDir, "test.txt");

  // A reporter that does nothing
  Reporter reporter = Reporter.NULL;
  
  int seed = new Random().nextInt();
  LOG.info("seed = "+seed);
  Random random = new Random(seed);

  localFs.delete(workDir, true);
  FileInputFormat.setInputPaths(job, workDir);

  // for a variety of lengths
  for (int length = 0; length < MAX_LENGTH;
       length+= random.nextInt(MAX_LENGTH/10)+1) {

    LOG.debug("creating; entries = " + length);

    // create a file with length entries
    Writer writer = new OutputStreamWriter(localFs.create(file));
    try {
      for (int i = 0; i < length; i++) {
        writer.write(Integer.toString(i));
        writer.write("\n");
      }
    } finally {
      writer.close();
    }

    // try splitting the file in a variety of sizes
    TextInputFormat format = new TextInputFormat();
    format.configure(job);
    LongWritable key = new LongWritable();
    Text value = new Text();
    for (int i = 0; i < 3; i++) {
      int numSplits = random.nextInt(MAX_LENGTH/20)+1;
      LOG.debug("splitting: requesting = " + numSplits);
      InputSplit[] splits = format.getSplits(job, numSplits);
      LOG.debug("splitting: got =        " + splits.length);

      if (length == 0) {
         assertEquals("Files of length 0 are not returned from FileInputFormat.getSplits().", 
                      1, splits.length);
         assertEquals("Empty file length == 0", 0, splits[0].getLength());
      }

      // check each split
      BitSet bits = new BitSet(length);
      for (int j = 0; j < splits.length; j++) {
        LOG.debug("split["+j+"]= " + splits[j]);
        RecordReader<LongWritable, Text> reader =
          format.getRecordReader(splits[j], job, reporter);
        try {
          int count = 0;
          while (reader.next(key, value)) {
            int v = Integer.parseInt(value.toString());
            LOG.debug("read " + v);
            if (bits.get(v)) {
              LOG.warn("conflict with " + v + 
                       " in split " + j +
                       " at position "+reader.getPos());
            }
            assertFalse("Key in multiple partitions.", bits.get(v));
            bits.set(v);
            count++;
          }
          LOG.debug("splits["+j+"]="+splits[j]+" count=" + count);
        } finally {
          reader.close();
        }
      }
      assertEquals("Some keys in no partition.", length, bits.cardinality());
    }

  }
}
 
Example 20
Project: dacapobench   File: Page.java   Source Code and License Vote up 2 votes
/**
 * Write a string to a log file
 * @param logFile
 * @param replyString
 * @throws IOException
 */
protected void writeLog(File logFile, String replyString) throws IOException {
  Writer output = new FileWriter(logFile);
  output.write(replyString);
  output.close();
}