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

The following are Jave code examples for showing how to use close() of the java.io.FileWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: pdf-converter   File: TxtCreator.java   View Source Code Vote up 7 votes
public void process(File pdf, File output){
        PDDocument pdDoc;
        try {//Kudos for closing: http://stackoverflow.com/questions/156508/closing-a-java-fileinputstream
            File tmpfile = File.createTempFile(String.format("txttmp-%s", UUID.randomUUID().toString()), null);
            RandomAccessFile raf = new RandomAccessFile(tmpfile, "rw");
            pdDoc = PDDocument.loadNonSeq(pdf, raf);
            FileWriter writer = new FileWriter(output);
            try {
                PDFTextStripper stripper = new PDFTextStripper();
                int numberOfPages = pdDoc.getNumberOfPages();

                for (int j = 1; j < numberOfPages+1; j++) {
                    stripper.setStartPage(j);
                    stripper.setEndPage(j);
                    writer.write(stripper.getText(pdDoc));
                    writer.flush();
                }
            } finally {
                pdDoc.close();
                raf.close();
                tmpfile.delete();
                writer.close();
            }
        } catch (IOException ioe) {
//            log.warn(String.format("Failed to create txt for file: %s", pdf.getName()), ioe);
        }
    }
 
Example 2
Project: featurea   File: SummaryDialog.java   View Source Code Vote up 6 votes
private void btnSaveAsActionPerformed(ActionEvent paramActionEvent) {
    JFileChooser localJFileChooser = new JFileChooser();
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("html", "HTML Files"));
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("doc", "Document Files"));
    localJFileChooser.addChoosableFileFilter(new JavaFileFilter("txt", "Text Files"));
    int i = localJFileChooser.showSaveDialog(this);
    if (i != 0) {
        return;
    }
    String str = localJFileChooser.getSelectedFile().getAbsolutePath();
    try {
        FileWriter localFileWriter = new FileWriter(str, false);
        localFileWriter.write(this.txtSumary.getText());
        localFileWriter.close();
    } catch (FileNotFoundException localFileNotFoundException) {
        localFileNotFoundException.printStackTrace();
        return;
    } catch (IOException localIOException) {
        localIOException.printStackTrace();
        return;
    }
}
 
Example 3
Project: PACE   File: LocalEncryptionKeyContainerTest.java   View Source Code Vote up 6 votes
@Test
public void writeReadTest() throws Exception {
  LocalEncryptionKeyContainer container = new LocalEncryptionKeyContainer();
  container.addKey("a", "b", 1, new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
  container.addKey("a", "b", 2, new byte[] {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2});
  container.addKey("d", 3, new byte[] {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3});
  container.addKey("d", 4, new byte[] {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4});

  File file = folder.newFile();
  FileWriter writer = new FileWriter(file);
  container.write(writer);
  writer.flush();
  writer.close();

  LocalEncryptionKeyContainer container2 = LocalEncryptionKeyContainer.read(new FileReader(file));
  assertThat("has matching keys", container2.getAttributeKey("a", "b", 1, 16), equalTo(container.getAttributeKey("a", "b", 1, 16)));
  assertThat("has matching keys", container2.getAttributeKey("a", "b", 2, 16), equalTo(container.getAttributeKey("a", "b", 2, 16)));
  assertThat("has matching keys", container2.getKey("d", 3, 16), equalTo(container.getKey("d", 3, 16)));
  assertThat("has matching keys", container2.getKey("d", 4, 16), equalTo(container.getKey("d", 4, 16)));
}
 
Example 4
Project: Tarski   File: UniverseCreateForKodKod.java   View Source Code Vote up 6 votes
public static void main(String[] args) {

    int size = 100;
    creatStr(size, size);
    createFile(size);
    createDir(size);
    createRoot();
    createContents(size, size);

    str += "\n\ncontents in Dir -> (Dir + File)\n" + "all d:Dir | not (d in d.^contents)\n"
        + "Root in Dir\n" + "(File + Dir) in Root.*contents";
    System.out.println(str);

    File tempFile = new File(
        "./../eu.modelwriter.traceability.validation.core.crocopat/files/KodKodTestFile.kodkod");

    try {
      FileWriter fileWriter = new FileWriter(tempFile);
      fileWriter.write(str);
      fileWriter.flush();
      fileWriter.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 
Example 5
Project: dashboard1b   File: WReportR.java   View Source Code Vote up 5 votes
@Override
public void log(String datos) {
	File file = new File("log.txt");
	try {
		FileWriter fW = new FileWriter(file, true);
		fW.write(new Date() + " - " + datos + "\n");
		fW.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
Example 6
Project: parabuild-ci   File: CodeSwitcher.java   View Source Code Vote up 5 votes
static void writeFileLines(Vector v, File f) throws IOException {

        FileWriter write = new FileWriter(f);

        for (int i = 0; i < v.size(); i++) {
            write.write((String) v.elementAt(i));
            write.write(ls);
        }

        write.flush();
        write.close();
    }
 
Example 7
Project: TextEmoji   File: FileAccessUtils.java   View Source Code Vote up 5 votes
public static void write(String path, String data) {
    if (!TextUtils.isEmpty(path)) {
        try {
            FileWriter writer = new FileWriter(path);
            writer.write(data);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
Example 8
Project: voogasalad-ltub   File: XStreamHandler.java   View Source Code Vote up 5 votes
public void saveToFile(Object data, File location){
	XStream xstream = new XStream(new DomDriver());
	String content = xstream.toXML(data);
	try {
		FileWriter fileWriter = new FileWriter(location);
		fileWriter.write(content);
		fileWriter.close();
	} catch (Exception e) {
		// user clicked cancel. No need to exclaim anything went wrong
	}
}
 
Example 9
Project: ibm-cos-sdk-java   File: FileUtils.java   View Source Code Vote up 5 votes
/**
 * Appends the given data to the file specified in the input and returns the
 * reference to the file.
 * 
 * @param file
 * @param dataToAppend
 * @return reference to the file.
 * @throws IOException
 */
public static File appendDataToTempFile(File file, String dataToAppend)
        throws IOException {
    FileWriter outputWriter = new FileWriter(file);

    try {
        outputWriter.append(dataToAppend);
    } finally {
        outputWriter.close();
    }

    return file;
}
 
Example 10
Project: oscm   File: VOConverterTestGenerator.java   View Source Code Vote up 5 votes
@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
    Class[] voClassesInPackage = getClasses(VO_VERSION_PACKAGE);
    VOConverterTestGenerator generator = new VOConverterTestGenerator(
            voClassesInPackage);
    FileWriter fw = null;
    try {
        fw = generator.createOutputFile();
        generator.writeCode(fw);
    } finally {
        if (fw != null) {
            fw.close();
        }
    }
}
 
Example 11
Project: sourcehelper   File: Writer.java   View Source Code Vote up 5 votes
private static void writerToFile(File file, String contents) throws Throwable {

		if (!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}

		FileWriter filewriter = new FileWriter(file);
		filewriter.write(contents);
		filewriter.flush();
		filewriter.close();
	}
 
Example 12
Project: DAA_Converter   File: MAF_Streamer.java   View Source Code Vote up 5 votes
private static void writeFile(String output, File file, boolean append) {
	try {
		FileWriter writer = new FileWriter(file, append);
		writer.write(output);
		writer.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: rlc-analyser   File: RLCDataExporter.java   View Source Code Vote up 5 votes
/**
 * The export method is used to carry out the writing to the CSV File. This
 * method calls other helper methods which perform the writing operations.
 *
 * @param csvFilePath path to which the file will be exported.
 * @throws IOException
 */
public void export(final String csvFilePath) throws IOException {

	final FileWriter writer = new FileWriter(csvFilePath);
	try {
		// Total Number of Components
		writeHeader(writer, "Component Summary");
		totalCounts(writer);

		CSVUtils.writeLine(writer, Arrays.asList("")); // empty line

		// Total Number of sub-types of the Components such as Comm Points, Routes, Filters and Definitions.
		writeHeader(writer, "Total Number of types of Components");
		totalCommPointTypes(writer);
		// general properties of each comm point:
		generalProperties(writer);
		totalFilterTypes(writer);
		totalFilterCountsPerRoute(writer);
		totalDefinitionsCountsPerRoute(writer);
		totalDefinitionTypes(writer);
		// Add the Rhapsody Version numbers
		rhapsodyVersionNumbers(writer);

		writer.flush();
	} finally {
		writer.close();
	}
}
 
Example 14
Project: openjdk-jdk10   File: T7068451.java   View Source Code Vote up 5 votes
static File writeFile(File base, String path, String body) throws IOException {
    File f = new File(base, path);
    FileWriter out = new FileWriter(f);
    out.write(body);
    out.close();
    System.err.println("wrote " + path + ": " + body);
    return f;
}
 
Example 15
Project: flume-release-1.7.0   File: TestDatasetSink.java   View Source Code Vote up 5 votes
@BeforeClass
public static void saveSchema() throws IOException {
  oldTestBuildDataProp = System.getProperty(TEST_BUILD_DATA_KEY);
  System.setProperty(TEST_BUILD_DATA_KEY, DFS_DIR);
  FileWriter schema = new FileWriter(SCHEMA_FILE);
  schema.append(RECORD_SCHEMA.toString());
  schema.close();
}
 
Example 16
Project: wbczq   File: FileUtil.java   View Source Code Vote up 5 votes
public static void clearFile(File file){
      try {
      	if(file != null && file.exists() && file.isFile()){
      		FileWriter fileWriter =new FileWriter(file);
      		fileWriter.write("");
      		fileWriter.flush();
      		fileWriter.close();        		
      	}
} catch (IOException e) {
	e.printStackTrace();
}
  }
 
Example 17
Project: code-sentinel   File: MindInspectorAgArch.java   View Source Code Vote up 5 votes
protected void addAgState() {
    try {
        Document state = getTS().getAg().getAgState(); // the XML representation of the agent's mind
        String sMind = getAgStateAsString(state, true);
        if (sMind.equals(lastHistoryText)) 
            return;
        lastHistoryText = sMind;

        if (mindInspectorPanel != null) { // output on GUI
            if (mindInspectorFreeze == null || !mindInspectorFreeze.isSelected())
                showAgState(state);
            if (mindInspectorHistory != null) {
                mindInspectorHistory.add(state);
                setupSlider(); 
                mindInspectorHistorySlider.setValue(mindInspectorHistory.size()-1);
            }
        } else if (mindInspectorDirectory != null) { // output on file
            String filename = String.format("%6d.xml",fileCounter++).replaceAll(" ","0");
            FileWriter outmind = new FileWriter(new File(mindInspectorDirectory+"/"+filename));
            outmind.write(sMind);
            outmind.close();
        } else if (webServer != null) { // output on web
            webServer.addAgState(getTS().getAg(), state, hasHistory);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: jdk8u-jdk   File: TwentyThousandTest.java   View Source Code Vote up 4 votes
public static void main(String[] args) throws Exception {
    tmpDir = System.getProperty("java.io.tmpdir");

    if (tmpDir.length() == 0) { //'java.io.tmpdir' isn't guaranteed to be defined
        tmpDir = System.getProperty("user.home");
    }

    System.out.println("Temp directory: " + tmpDir);

    System.out.println("Creating " + FILES + " files");

    for (int i = 0; i < FILES; i++) {
        File file = getTempFile(i);

        FileWriter writer = new FileWriter(file);
        writer.write("File " + i);
        writer.close();
    }

    for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
        if (laf.getClassName().contains("Motif")) {
            continue;
        }

        UIManager.setLookAndFeel(laf.getClassName());

        System.out.println("Do " + ATTEMPTS + " attempts for " + laf.getClassName());

        for (int i = 0; i < ATTEMPTS; i++) {
            System.out.print(i + " ");

            doAttempt();
        }

        System.out.println();
    }

    System.out.println("Removing " + FILES + " files");

    for (int i = 0; i < FILES; i++) {
        getTempFile(i).delete();
    }

    System.out.println("Test passed successfully");
}
 
Example 19
Project: StackNet   File: KerasnnRegressor.java   View Source Code Vote up 4 votes
/**
* 
* @param filename : the conifiguration file name for required to run xgboost from the command line
* @param datset : the dataset to be used
* @param model : model dump name
* @param columns : Number of columns in the data
*/
 private void create_config_file(String filename , String datset, String model, int columns){

try{  // Catch errors in I/O if necessary.
	  // Open a file to write to.
	
		String saveFile = filename;
		
		FileWriter writer = new FileWriter(saveFile);
		writer.append("task=train\n");
	    writer.append("columns=" + columns+ "\n");					
	    writer.append("usedense=" + this.use_dense+ "\n");	
	    writer.append("standardize=" + this.standardize+ "\n");	
	    writer.append("use_log1p=" + this.use_log1p+ "\n");				    
	    writer.append("model=" +model+ "\n");	
	    writer.append("data=" +datset+ "\n");				    
	    writer.append("l2=" + this.l2+ "\n");
	    writer.append("momentum=" + this.momentum  + "\n");
	    writer.append("epochs=" +this.epochs + "\n");
	    writer.append("batch_size=" + this.batch_size + "\n");
	    writer.append("stopping_rounds=" + this.stopping_rounds+ "\n");
	    writer.append("threads=" + this.threads + "\n");
	    writer.append("validation_split=" + this.validation_split + "\n");
	    writer.append("seed=" + this.seed  + "\n");
	    writer.append("lr=" + this.lr + "\n");
	    writer.append("shuffle=" + this.shuffle + "\n");
	    writer.append("hidden=" + this.hidden + "\n");
	    writer.append("droupouts=" +  this.droupouts + "\n");
	    writer.append("weight_init=" +  this.weight_init + "\n");
	    writer.append("batch_normalization=" +  this.batch_normalization + "\n");			    
	    writer.append("activation=" + this.activation + "\n");
	    writer.append("optimizer=" +  this.optimizer + "\n");
	    writer.append("loss=" +  this.loss + "\n");			    
	    if (this.verbose){
	    	writer.append("verbose=1" +  "\n");
	    }else {
	    	writer.append("verbose=0" +  "\n");			    	
	    }		    
		writer.close();

   	} catch (Exception e) {
   		throw new IllegalStateException(" failed to write the config file at: " + filename);
   	}   
 }
 
Example 20
Project: StackNet   File: SklearnMLPRegressor.java   View Source Code Vote up 4 votes
/**
* 
* @param filename : the conifiguration file name for required to run xgboost from the command line
* @param datset : the dataset to be used
* @param model : model dump name
* @param columns : Number of columns in the data
*/
 private void create_config_file(String filename , String datset, String model, int columns){

try{  // Catch errors in I/O if necessary.
	  // Open a file to write to.
	
		String saveFile = filename;
		
		FileWriter writer = new FileWriter(saveFile);
		writer.append("task=train\n");
	    writer.append("columns=" + columns+ "\n");					
	    writer.append("usedense=" + this.use_dense+ "\n");	
	    writer.append("standardize=" + this.standardize+ "\n");	
	    writer.append("use_log1p=" + this.use_log1p+ "\n");				    
	    writer.append("model=" +model+ "\n");	
	    writer.append("data=" +datset+ "\n");				    
	    writer.append("alpha=" + this.alpha+ "\n");
	    writer.append("momentum=" + this.momentum  + "\n");
	    writer.append("max_iter=" +this.epochs + "\n");
	    writer.append("batch_size=" + this.batch_size + "\n");
	    writer.append("validation_fraction=" + this.validation_split + "\n");
	    writer.append("random_state=" + this.seed  + "\n");
	    writer.append("learning_rate_init=" + this.learning_rate_init + "\n");
	    writer.append("shuffle=" + this.shuffle + "\n");
	    writer.append("hidden_layer_sizes=" + this.hidden + "\n");
	    writer.append("tol=" +  this.tol + "\n");
	    writer.append("learning_rate=" +  this.learning_rate + "\n");		    
	    writer.append("activation=" + this.activation + "\n");
	    writer.append("solver=" +  this.optimizer + "\n");
	    writer.append("epsilon=" +  this.epsilon + "\n");			    
	    if (this.verbose){
	    	writer.append("verbose=1" +  "\n");
	    }else {
	    	writer.append("verbose=0" +  "\n");			    	
	    }		    
		writer.close();

   	} catch (Exception e) {
   		throw new IllegalStateException(" failed to write the config file at: " + filename);
   	}   
 }