下面列出了java.io.BufferedWriter#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("./tmpdata/trad.txt"), "UTF-8"));
SougouCA sca = new SougouCA("./tmpdata/SogouCa/news.allsites.010805.txt");
while(sca.hasNext()){
String s = (String) sca.next().getData();
s = tc.normalize(s);
// System.out.println(s);
if (s.length() == 0)
continue;
bout.write(s);
bout.write("\n");
}
bout.close();
System.out.println("Done!");
}
/**
* Listing the encodings of font comic.
*
* @param args
* no arguments needed
*/
@Test
public void main() throws Exception {
File font = new File(PdfTestBase.RESOURCES_DIR + "liberation-fonts-ttf/LiberationMono-Regular.ttf");
BufferedWriter out = new BufferedWriter(new FileWriter(PdfTestBase.OUTPUT_DIR + "encodings.txt"));
BaseFont bfComic = BaseFont.createFont(font.getAbsolutePath(), BaseFont.CP1252,
BaseFont.NOT_EMBEDDED);
out.write("postscriptname: " + bfComic.getPostscriptFontName());
out.write("\r\n\r\n");
String[] codePages = bfComic.getCodePagesSupported();
out.write("All available encodings:\n\n");
for (int i = 0; i < codePages.length; i++) {
out.write(codePages[i]);
out.write("\r\n");
}
out.flush();
out.close();
}
/**
* Saves the metrics to a file for it to be reloaded when the crawler restarts
*
* @param metricsRegistry
* @param directoryPath
* @throws IOException
*/
private void saveMetrics(MetricRegistry metricsRegistry, String directoryPath) {
String directoryName = directoryPath + "/metrics/";
File file = new File(directoryName);
if (file.exists()) {
file.delete();
}
file.mkdir();
try {
File outputFile = new File(directoryName + "metrics_counters.data");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
SortedMap<String, Counter> counters = metrics.getCounters();
for (String counter : counters.keySet()) {
Counter c = counters.get(counter);
writer.write(counter + ":" + c.getCount());
writer.newLine();
writer.flush();
}
writer.flush();
writer.close();
} catch (IOException e) {
logger.error("Unable to save metrics to a file." + e.getMessage());
}
}
private static void printResults(String file, double[][] results) {
try {
// Create file
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write("maj-high\tmaj-low\ttog-high\ttog-low\tsi-high\tsi-low\n");
for (int i = 0; i < results[0].length; i++) {
for (int j = 0; j < results.length; j++) {
out.write(results[j][i] + "\t");
}
out.write("\n");
}
out.flush();
// Close the output stream
fstream.flush();
out.close();
fstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void semEvalTest() throws Exception
{
Arrays.sort(FramesSemEval.testSet);
sentenceNum = 0;
BufferedWriter bWriterFrames = new BufferedWriter(new FileWriter("/mal2/dipanjan/experiments/FramenetParsing/framenet_1.3/ddData/semeval.fulltest.sentences.frames"));
BufferedWriter bWriterFEs = new BufferedWriter(new FileWriter("/mal2/dipanjan/experiments/FramenetParsing/framenet_1.3/ddData/semeval.fulltest.sentences.frame.elements"));
for(int j = 0; j < FramesSemEval.testSet.length; j ++)
{
String fileName = FramesSemEval.testSet[j];
System.out.println("\n\n"+fileName);
getSemEvalFrames(fileName,bWriterFrames);
getSemEvalFrameElements(fileName,bWriterFEs);
}
bWriterFrames.close();
bWriterFEs.close();
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length != 2 && args.length != 3) {
System.err.println("USAGE: LogFormatter <log|snapshot> log_file");
System.exit(2);
}
if (args.length == 3) {
bw = new BufferedWriter(new FileWriter(new File(args[2])));
}
if (args[0].equals("log")) {
readTransactionLog(args[1]);
} else if (args[0].equals("snapshot")) {
readSnapshotLog(args[1]);
}
if (bw != null) {
bw.close();
}
}
public void writeFileOfSize(final File file, final int size) {
try {
final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for (int i = 0; i < size; i++) {
final int toWrite = Math.min(1000, size);
final char[] writeBuffer = new char[toWrite];
for (int j = 0; j < writeBuffer.length; j++) {
writeBuffer[j] = (char) (Math.random() * 150);
}
writer.write(writeBuffer);
}
writer.flush();
writer.close();
} catch (final Exception exc) {
throw new RuntimeException(exc);
}
}
private void createFile(String content) throws Exception
{
file = File.createTempFile("RenameUserTest", ".txt");
args[4] = "-file";
args[5] = file.getPath();
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(content);
out.close();
}
private boolean write(final String filename, final List<Map<EnumTableColumn<?>, Object>> rows, final List<EnumTableColumn<?>> header, final String tableName, final boolean dropTable, final boolean createTable, final boolean extendedInserts) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename));
writeComment(writer);
writeTable(writer, rows, header, tableName, dropTable, createTable);
writeRows(writer, rows, header, tableName, extendedInserts);
writer.close();
} catch (IOException ex) {
LOG.warn("SQL file not saved");
return false;
}
LOG.info("SQL file saved");
return true;
}
@Before
public void setup() throws IOException {
downloader = new SimpleFileDownloader();
webserver = new WebServer();
updateRepoDir = Files.createTempDirectory("repo");
updateRepoDir.toFile().deleteOnExit();
repoFile = Files.createFile(updateRepoDir.resolve("myfile"));
BufferedWriter writer = new BufferedWriter(Files.newBufferedWriter(repoFile, Charset.forName("utf-8"), StandardOpenOption.APPEND));
writer.write("test");
writer.close();
emptyFile = Files.createFile(updateRepoDir.resolve("emptyFile"));
}
public static boolean processFile(String inputFile, String outputFile) {
try {
FileReader reader = new FileReader(new File("./data/csv/cul_core/" + inputFile));
FileWriter writer = new FileWriter(new File("./data/csv/cul_core/" + outputFile + ".txt"));
BufferedReader br = new BufferedReader(reader);
BufferedWriter bw = new BufferedWriter(writer);
String line = null;
String resID = "", userHash = "", timestamp = "";
List<String> tags = new ArrayList<String>();
while ((line = br.readLine()) != null) {
String[] lineParts = line.split("\\|");
String tag = lineParts[3];
if (!tag.isEmpty() && !tag.equals("no-tag") && !tag.contains("-import") && !tag.contains("-export") && !tag.contains("sys:") && !tag.contains("system:") && !tag.contains("imported")) {
if (!resID.isEmpty() && !userHash.isEmpty() && (!resID.equals(lineParts[0]) || !userHash.equals(lineParts[1]))) {
writeLine(bw, resID, userHash, timestamp, tags);
tags.clear();
}
resID = lineParts[0];
userHash = lineParts[1];
timestamp = lineParts[2];
tags.add(tag);
}
}
writeLine(bw, resID, userHash, timestamp, tags);
br.close();
bw.flush();
bw.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 追加写,为泰语编码 "ISO-8859-11"写入
*
* @param fileName
* @param content
*/
public static void appendThaiFile(File file, String content) {
try {
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-11");
BufferedWriter writer = new BufferedWriter(write);
writer.write(content);
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static File writeFile(File f, String str) throws IOException {
f.getParentFile().mkdirs();
BufferedWriter fout = new BufferedWriter(new FileWriter(f));
try {
fout.write(str);
fout.flush();
} finally {
fout.close();
}
return f;
}
public static void closeWriter (BufferedWriter writer) {
try {
writer.close();
}
catch (IOException ioe) {
throw new PicardException("Error closing BufferedWriter "+
": " + ioe.getMessage(), ioe);
}
}
public void test() throws Exception {
Path tempDir = createTempDir("64kaffixes");
Path affix = tempDir.resolve("64kaffixes.aff");
Path dict = tempDir.resolve("64kaffixes.dic");
BufferedWriter affixWriter = Files.newBufferedWriter(affix, StandardCharsets.UTF_8);
// 65k affixes with flag 1, then an affix with flag 2
affixWriter.write("SET UTF-8\nFLAG num\nSFX 1 Y 65536\n");
for (int i = 0; i < 65536; i++) {
affixWriter.write("SFX 1 0 " + Integer.toHexString(i) + " .\n");
}
affixWriter.write("SFX 2 Y 1\nSFX 2 0 s\n");
affixWriter.close();
BufferedWriter dictWriter = Files.newBufferedWriter(dict, StandardCharsets.UTF_8);
// drink signed with affix 2 (takes -s)
dictWriter.write("1\ndrink/2\n");
dictWriter.close();
try (InputStream affStream = Files.newInputStream(affix); InputStream dictStream = Files.newInputStream(dict); Directory tempDir2 = newDirectory()) {
Dictionary dictionary = new Dictionary(tempDir2, "dictionary", affStream, dictStream);
Stemmer stemmer = new Stemmer(dictionary);
// drinks should still stem to drink
List<CharsRef> stems = stemmer.stem("drinks");
assertEquals(1, stems.size());
assertEquals("drink", stems.get(0).toString());
}
}
private static void dumpToFile(String jsonStr, String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fw);
out.write(jsonStr);
out.close();
fw.close();
}
private static void generateOldDatafile() {
try {
FileWriter fout = new FileWriter(oldDatafile);
BufferedWriter bout = new BufferedWriter(fout);
bout.write("\n //\n // The following String[][] can be used in CharSet.java as is.\n //\n\n private static final String[][] categoryMap = {\n");
for (int i = 0; i < categoryNames.length - 1; i++) {
if (oldTotalCount[i] != 0) {
bout.write(" { \"" + categoryNames[i] + "\",");
/* 0x0000-0xD7FF */
if (oldListCount[BEFORE][i] != 0) {
bout.write(" \"");
bout.write(oldList[BEFORE][i].toString() + "\"\n");
}
/* 0xD800-0xFFFF */
if (oldListCount[AFTER][i] != 0) {
if (oldListCount[BEFORE][i] != 0) {
bout.write(" + \"");
} else {
bout.write(" \"");
}
bout.write(oldList[AFTER][i].toString() + "\"\n");
}
/* 0xD800DC00(0x10000)-0xDBFF0xDFFFF(0x10FFFF) */
if (oldListCount[SURROGATE][i] != 0) {
if (oldListCount[BEFORE][i] != 0 || oldListCount[AFTER][i] != 0) {
bout.write(" + \"");
} else {
bout.write(" \"");
}
bout.write(oldList[SURROGATE][i].toString() + "\"\n");
}
bout.write(" },\n");
}
}
bout.write(" };\n\n");
bout.close();
fout.close();
}
catch (Exception e) {
System.err.println("Error occurred on accessing " + oldDatafile);
e.printStackTrace();
System.exit(1);
}
System.out.println("\n" + oldDatafile + " has been generated.");
}
@Test
public void testRssStreamProvider() throws Exception {
final String configfile = "./target/test-classes/RssStreamProviderIT.conf";
final String outfile = "./target/test-classes/RssStreamProviderIT.stdout.txt";
InputStream is = RssStreamProviderIT.class.getResourceAsStream("/top100.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
RssStreamConfiguration configuration = new RssStreamConfiguration();
List<FeedDetails> feedArray = new ArrayList<>();
try {
while (br.ready()) {
String line = br.readLine();
if (!StringUtils.isEmpty(line)) {
feedArray.add(new FeedDetails().withUrl(line).withPollIntervalMillis(5000L));
}
}
configuration.setFeeds(feedArray);
} catch ( Exception ex ) {
ex.printStackTrace();
Assert.fail();
}
org.junit.Assert.assertThat(configuration.getFeeds().size(), greaterThan(70));
OutputStream os = new FileOutputStream(configfile);
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
// write conf
ObjectNode feedsNode = mapper.convertValue(configuration, ObjectNode.class);
JsonNode configNode = mapper.createObjectNode().set("rss", feedsNode);
bw.write(mapper.writeValueAsString(configNode));
bw.flush();
bw.close();
File config = new File(configfile);
assert (config.exists());
assert (config.canRead());
assert (config.isFile());
RssStreamProvider.main(new String[]{configfile, outfile});
File out = new File(outfile);
assert (out.exists());
assert (out.canRead());
assert (out.isFile());
FileReader outReader = new FileReader(out);
LineNumberReader outCounter = new LineNumberReader(outReader);
while (outCounter.readLine() != null) {}
assert (outCounter.getLineNumber() >= 200);
}
private static String convertAliases_2_2_to_2_3(ApplicationFiles appFiles)
{
if(appFiles.getDatabaseAliasesFile().exists())
{
return null;
}
if(false == appFiles.getDatabaseAliasesFile_before_version_2_3().exists())
{
return null;
}
try
{
FileReader fr = new FileReader(appFiles.getDatabaseAliasesFile_before_version_2_3());
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(appFiles.getDatabaseAliasesFile());
BufferedWriter bw = new BufferedWriter(fw);
String oldClassName = "net.sourceforge.squirrel_sql.fw.sql.SQLAlias";
String newClassName = SQLAlias.class.getName();
String line = br.readLine();
while(null != line)
{
int ix = line.indexOf(oldClassName);
if(-1 != ix)
{
line = line.substring(0,ix) + newClassName + line.substring(ix + oldClassName.length(), line.length());
}
bw.write(line + "\n");
line = br.readLine();
}
bw.flush();
fw.flush();
bw.close();
fw.close();
br.close();
fr.close();
return null;
}
catch (Exception e)
{
return "Conversion of Aliases file failed: Could not write new Aliases file named \n" +
appFiles.getDatabaseAliasesFile().getPath() + "\n" +
"You can not start this new version of SQuirreL using your existing Aliases.\n" +
"You may either continue to use your former SQuirreL version or remove file\n" +
appFiles.getDatabaseAliasesFile_before_version_2_3().getPath() + "\n" +
"for your first start of this SQuirreL version. SQuirreL will then try to create an empty Alias file named\n" +
appFiles.getDatabaseAliasesFile().getPath() + "\n" +
"Please contact us about this problem. Send a mail to [email protected]";
}
}
/**
* save the grid to file
*/
public void saveGrid(String filePath, int gridSize){
try{
// Create file
FileWriter fstream = new FileWriter(filePath);
BufferedWriter out = new BufferedWriter(fstream);
out.write("****:" + gridEEBL_.length + ":" + gridEEBL_[0].length + ":" + gridSize + "\n");
out.write("HUANG_EEBL\n");
for(int i = 0; i < gridEEBL_.length; i++){
for(int j = 0; j < gridEEBL_[0].length - 1; j++){
out.write(gridEEBL_[i][j] + ":");
}
out.write(gridEEBL_[i][gridEEBL_[0].length-1] + "\n");
}
out.write("HUANG_PCN\n");
for(int i = 0; i < gridPCN_.length; i++){
for(int j = 0; j < gridPCN_[0].length - 1; j++){
out.write(gridPCN_[i][j] + ":");
}
out.write(gridPCN_[i][gridPCN_[0].length-1] + "\n");
}
out.write("PCN_FORWARD\n");
for(int i = 0; i < gridPCNFORWARD_.length; i++){
for(int j = 0; j < gridPCNFORWARD_[0].length - 1; j++){
out.write(gridPCNFORWARD_[i][j] + ":");
}
out.write(gridPCNFORWARD_[i][gridPCNFORWARD_[0].length-1] + "\n");
}
out.write("HUANG_RHCN\n");
for(int i = 0; i < gridRHCN_.length; i++){
for(int j = 0; j < gridRHCN_[0].length - 1; j++){
out.write(gridRHCN_[i][j] + ":");
}
out.write(gridRHCN_[i][gridRHCN_[0].length-1] + "\n");
}
out.write("HUANG_EVA_FORWARD\n");
for(int i = 0; i < gridEVAFORWARD_.length; i++){
for(int j = 0; j < gridEVAFORWARD_[0].length - 1; j++){
out.write(gridEVAFORWARD_[i][j] + ":");
}
out.write(gridEVAFORWARD_[i][gridEVAFORWARD_[0].length-1] + "\n");
}
out.write("EVA_EMERGENCY_ID\n");
for(int i = 0; i < gridEVA_.length; i++){
for(int j = 0; j < gridEVA_[0].length - 1; j++){
out.write(gridEVA_[i][j] + ":");
}
out.write(gridEVA_[i][gridEVA_[0].length-1] + "\n");
}
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}