Java Code Examples for java.io.FileWriter#write()

The following examples show how to use java.io.FileWriter#write() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Criteria2Query   File: CmdUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static int save2File(String fileName, String content) {
	File file = new File(fileName);
	try {
		// if the file is not exist, create it!
		if (file.exists() == false) {

			file.createNewFile();

		}
		// the second parameter is 'true' means add contents at the end of
		// the file
		FileWriter writer = new FileWriter(fileName);
		writer.write(content);
		writer.close();
		return 1;
	} catch (IOException e) {
		e.printStackTrace();
		return 0;
	}

}
 
Example 2
Source Project: netbeans   File: BasicTest.java    License: Apache License 2.0 6 votes vote down vote up
public void compareGoldenFile() throws IOException {
    File fGolden = null;
    if(!generateGoldenFiles) {
        fGolden = getGoldenFile();
    } else {
        fGolden = getNewGoldenFile();
    }
    String refFileName = getName()+".ref";
    String diffFileName = getName()+".diff";
    File fRef = new File(getWorkDir(),refFileName);
    FileWriter fw = new FileWriter(fRef);
    fw.write(oper.getText());
    fw.close();
    LineDiff diff = new LineDiff(false);
    if(!generateGoldenFiles) {
        File fDiff = new File(getWorkDir(),diffFileName);
        if(diff.diff(fGolden, fRef, fDiff)) fail("Golden files differ");
    } else {
        FileWriter fwgolden = new FileWriter(fGolden);
        fwgolden.write(oper.getText());
        fwgolden.close();
        fail("Golden file generated");
    }
}
 
Example 3
Source Project: openapi-diff   File: OpenApiDiffTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNewApi() {
  ChangedOpenApi changedOpenApi = OpenApiCompare.fromLocations(OPENAPI_EMPTY_DOC, OPENAPI_DOC2);
  List<Endpoint> newEndpoints = changedOpenApi.getNewEndpoints();
  List<Endpoint> missingEndpoints = changedOpenApi.getMissingEndpoints();
  List<ChangedOperation> changedEndPoints = changedOpenApi.getChangedOperations();
  String html =
      new HtmlRender("Changelog", "http://deepoove.com/swagger-diff/stylesheets/demo.css")
          .render(changedOpenApi);

  try {
    FileWriter fw = new FileWriter("target/testNewApi.html");
    fw.write(html);
    fw.close();

  } catch (IOException e) {
    e.printStackTrace();
  }
  assertThat(newEndpoints).isNotEmpty();
  assertThat(missingEndpoints).isEmpty();
  assertThat(changedEndPoints).isEmpty();
}
 
Example 4
Source Project: netbeans   File: TokenDumpCheck.java    License: Apache License 2.0 6 votes vote down vote up
public void finish() throws Exception {
    if (input == null) {
        if (!outputFile.createNewFile()) {
            NbTestCase.fail("Cannot create file " + outputFile);
        }
        FileWriter fw = new FileWriter(outputFile);
        try {
            fw.write(output.toString());
        } finally {
            fw.close();
        }
        NbTestCase.fail("Created tokens dump file " + outputFile + "\nPlease re-run the test.");

    } else {
        if (inputIndex < input.length()) {
            NbTestCase.fail("Some text left unread:" + input.substring(inputIndex));
        }
    }
}
 
Example 5
Source Project: netbeans   File: BasicTest.java    License: Apache License 2.0 5 votes vote down vote up
public void compareGoldenFile() throws IOException, InterruptedException {
    File fGolden = null;
    if(!generateGoldenFiles) {
        fGolden = getGoldenFile(testClass+".pass");
    } else {
        fGolden = getNewGoldenFile();
    }
    String refFileName = getName()+".ref";
    String diffFileName = getName()+".diff";
    File fRef = new File(getWorkDir(),refFileName);
    Thread.sleep(1000);
    FileWriter fw = new FileWriter(fRef);
    fw.write(oper.getText());
    fw.close();
    Thread.sleep(1000);
   // LineDiff diff = new LineDiff(false);
    if(!generateGoldenFiles) {
        File fDiff = new File(getWorkDir(),diffFileName);
        System.out.println("fRef file is: "+fRef);
        System.out.println("fGolden file is: "+fGolden);
        System.out.println("fDiff file is: "+fDiff);
        assertFile(fRef, fGolden, fDiff);
        Thread.sleep(1000);
       // if(diff.diff(fGolden, fRef, fDiff)) fail("Golden files differ");
    } else {
        FileWriter fwgolden = new FileWriter(fGolden);
        fwgolden.write(oper.getText());
        fwgolden.close();
        fail("Golden file generated");
    }
}
 
Example 6
File writeFile(File f, String text) throws IOException {
    f.getParentFile().mkdirs();
    FileWriter fw = new FileWriter(f);
    try {
        fw.write(text);
    } finally {
        fw.close();
    }
    return f;
}
 
Example 7
Source Project: oim-fx   File: ShowAccountDialog.java    License: MIT License 5 votes vote down vote up
public void writeFile(String fileName) {
	try {
		File f = new File(fileName);
		FileWriter write = new FileWriter(f);
		String text = textArea.getText();
		write.write(text);
		write.close();
	} catch (Exception e) {
		this.showPrompt("保存失败");
	}
}
 
Example 8
/** Adds a line to a file. **/
public static void appendFile(String content, String... file) {
	try {
		FileWriter writer = new FileWriter(stringsToPath(file).toFile(), true);
		writer.write(content + "\n");
		writer.close();
	} catch (IOException e) { System.out.println("Error Appending File: " + file); e.printStackTrace(); } 
}
 
Example 9
Source Project: dynamico   File: FileDownload.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onResponse() throws Exception {
    if(file.exists()) {
        file.delete();
    }

    file.createNewFile();

    FileWriter writer = new FileWriter(file);
    writer.write(output);
    writer.close();
}
 
Example 10
Source Project: uavstack   File: IOHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void write(String line, String filename) {

        try {
            FileWriter fw = new FileWriter(filename);
            fw.write(line);
            fw.flush();
            fw.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
 
Example 11
File writeFile(File f, String text) throws IOException {
    f.getParentFile().mkdirs();
    FileWriter fw = new FileWriter(f);
    try {
        fw.write(text);
    } finally {
        fw.close();
    }
    return f;
}
 
Example 12
@Test
public void testFindAllAfterChangeInFile() throws IOException {
    TestDataProviderEngine engine = new TestDataProviderEngine();
    engine.setResourceLoader(new DefaultResourceLoader());
    engine.setPathOnDisk(testFolder.getRoot() + "/");

    N2oTestDataProvider provider = new N2oTestDataProvider();
    provider.setFile(testFile.getName());

    //Проверка исходных данных в файле
    List<Map> result = (List<Map>) engine.invoke(provider, new LinkedHashMap<>());
    assertThat(result.size(), is(1));
    assertThat(result.get(0).get("id"), is(1L));
    assertThat(result.get(0).get("name"), is("test1"));
    assertThat(result.get(0).get("type"), is("1"));

    //Добавление новых данных
    FileWriter fileWriter = new FileWriter(testFile);
    fileWriter.write("[" +
            "{\"id\":9, \"name\":\"test9\", \"type\":\"9\"}," +
            "{\"id\":1, \"name\":\"test1\", \"type\":\"1\"}" +
            "]");
    fileWriter.close();

    //Проверка, что после изменения json, новые данные будут возвращены
    result = (List<Map>) engine.invoke(provider, new LinkedHashMap<>());
    assertThat(result.size(), is(2));
    assertThat(result.get(0).get("id"), is(9L));
    assertThat(result.get(0).get("name"), is("test9"));
    assertThat(result.get(0).get("type"), is("9"));
    assertThat(result.get(1).get("id"), is(1L));
    assertThat(result.get(1).get("name"), is("test1"));
    assertThat(result.get(1).get("type"), is("1"));
}
 
Example 13
File writeFile(File f, String text) throws IOException {
    f.getParentFile().mkdirs();
    FileWriter fw = new FileWriter(f);
    try {
        fw.write(text);
    } finally {
        fw.close();
    }
    return f;
}
 
Example 14
private void runPresentationProgram() {
    if (factory == null) {
        if (input == null) {
            JOptionPane.showMessageDialog(null, "No model input has been selected yet", "Select cases", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        factory = ApplicationRunner.createStochModelFactoryComponent(input);
    }

// TODO    
//    if (!(factory instanceof IStochModelPostProcessor)) {
//        JOptionPane.showMessageDialog(null, "Chosen model has no postprocessing counterpart", "Select cases", JOptionPane.INFORMATION_MESSAGE);
//        return;
//    }

    try {
        FileWriter writer = new FileWriter(new File(BBUtils.getFileNameWithoutExtension(input.getAbsolutePath()) + ".oap"), true);
        for (int i = 0; i < selectedCases.getSize(); i ++) {
            StoredResult selectedResult = (StoredResult) selectedCases.getElementAt(i);
            postProcessor = factory.getPostprocessorInstance(new File(input.getParent(), selectedResult.getDirectory()));
            postProcessor.produceAdditionalOutput();

            writer.write(selectedResult.getDirectory() + "\n");
            writer.write(selectedResult.toString() + "\n");
        }

        writer.close();

        fillLists();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "Error while producing presentations:\n"
            + e.getMessage(), "Select cases", JOptionPane.INFORMATION_MESSAGE);
    }

    //
}
 
Example 15
Source Project: Aurora   File: UUIDS.java    License: Apache License 2.0 5 votes vote down vote up
private void saveDCIMFile(String id) {
    try {
        File file = new File(FILE_DCIM);
        FileWriter writer = new FileWriter(file);
        writer.write(id);
        writer.flush();
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
private void test(boolean expressions, TSResourceFormat resourceFormat) throws IOException {
	outputDir = new File("build/tmp/gen");
	FileUtils.deleteDirectory(outputDir);
	outputDir.mkdirs();

	File npmrcFile = new File(outputDir, ".npmrc");
	FileWriter npmrcWriter = new FileWriter(npmrcFile);
	npmrcWriter.write("");
	npmrcWriter.close();


	MetaLookup lookup = createLookup();

	TSGeneratorModule module = new TSGeneratorModule();
	createConfig(module.getConfig(), resourceFormat, expressions);
	module.getConfig().setGenDir(outputDir);
	module.initDefaults(outputDir);
	module.generate(lookup);

	assertExists("index.ts");
	assertExists("index.ts");
	assertExists("projects.ts");
	assertExists("primitive.attribute.ts");
	assertExists("types/project.data.ts");
	assertExists("schedule.ts");
	assertExists("tasks.ts");
	assertExists("facet.ts");
	assertExists("facet.value.ts");
	assertExists("some/dotted.resource.ts");
	if (resourceFormat == TSResourceFormat.PLAINJSON) {
		assertExists("crnk.ts");

		checkPrimitiveAttributes();
	}
	assertNotExists("tasks.links.ts");
	assertNotExists("tasks.meta.ts");

	checkSchedule(expressions, resourceFormat);
	checkProject();
	if (expressions) {
		checkProjectData();
	}
}
 
Example 17
Source Project: hadoop   File: TestHardLink.java    License: Apache License 2.0 4 votes vote down vote up
private void makeNonEmptyFile(File file, String contents) 
throws IOException {
  FileWriter fw = new FileWriter(file);
  fw.write(contents);
  fw.close();
}
 
Example 18
@Test
public void testReadCorruptedProjectJson() throws IOException, CoreException {
	IMetaStore metaStore = null;
	try {
		metaStore = OrionConfiguration.getMetaStore();
	} catch (NullPointerException e) {
		// expected when the workbench is not running
	}
	if (!(metaStore instanceof SimpleMetaStore)) {
		// the workbench is not running, just pass the test
		return;
	}

	// create the user
	UserInfo userInfo = new UserInfo();
	userInfo.setUserName(testUserLogin);
	userInfo.setFullName(testUserLogin);
	metaStore.createUser(userInfo);

	// create the workspace
	String workspaceName = SimpleMetaStore.DEFAULT_WORKSPACE_NAME;
	WorkspaceInfo workspaceInfo = new WorkspaceInfo();
	workspaceInfo.setFullName(workspaceName);
	workspaceInfo.setUserId(userInfo.getUniqueId());
	metaStore.createWorkspace(workspaceInfo);

	// create a folder and project.json for the bad project on the filesystem
	String projectName = "Bad Project";
	File rootLocation = OrionConfiguration.getRootLocation().toLocalFile(EFS.NONE, null);
	String workspaceId = SimpleMetaStoreUtil.encodeWorkspaceId(userInfo.getUniqueId(), workspaceName);
	String encodedWorkspaceName = SimpleMetaStoreUtil.decodeWorkspaceNameFromWorkspaceId(workspaceId);
	File userMetaFolder = SimpleMetaStoreUtil.readMetaUserFolder(rootLocation, userInfo.getUniqueId());
	File workspaceMetaFolder = SimpleMetaStoreUtil.readMetaFolder(userMetaFolder, encodedWorkspaceName);

	assertTrue(SimpleMetaStoreUtil.createMetaFolder(workspaceMetaFolder, projectName));
	String corruptedProjectJson = "{\n\"OrionVersion\": 4,";
	File newFile = SimpleMetaStoreUtil.retrieveMetaFile(userMetaFolder, projectName);
	FileWriter fileWriter = new FileWriter(newFile);
	fileWriter.write(corruptedProjectJson);
	fileWriter.write("\n");
	fileWriter.flush();
	fileWriter.close();

	// read the project, should return null as the project is corrupted on disk
	ProjectInfo readProjectInfo = metaStore.readProject(workspaceInfo.getUniqueId(), projectName);
	assertNull(readProjectInfo);
}
 
Example 19
Source Project: tianti   File: GenCodeUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 创建Dao类
 * @param c实体类
 * @param commonPackage 基础包:如com.jeff.tianti.info
 * @throws IOException
 */
public static void createDaoClass(Class c,String commonPackage,String author) throws IOException{
	String cName = c.getName();
	String daoPath = "";
	if(author == null || author.equals("")){
		author = "Administrator";
	}
	if(commonPackage != null && !commonPackage.equals("")){
		daoPath = commonPackage.replace(".", "/");
		String fileName = System.getProperty("user.dir") + "/src/main/java/" + daoPath+"/dao"
				+ "/" + getLastChar(cName) + "DaoImpl.java";
		File f = new File(fileName);
		FileWriter fw = new FileWriter(f);
		fw.write("package "+commonPackage+".dao"+";"+RT_2+"import com.jeff.tianti.common.dao.CustomBaseSqlDaoImpl;"+RT_1
				+"import com.jeff.tianti.common.entity.PageModel;"+RT_1
				+"import java.util.HashMap;"+RT_1
				+"import java.util.List;"+RT_1
				+"import java.util.Map;"+RT_1
				+"import "+commonPackage+".entity"+"."+getLastChar(cName)+";"+RT_1
				+"import "+commonPackage+".dto"+"."+getLastChar(cName)+"QueryDTO;"+RT_1
				+"/**"+RT_1+BLANK_1+"*"+BLANK_1+ANNOTATION_AUTHOR_PARAMTER+ author +RT_1
				+BLANK_1+"*"+BLANK_1+ANNOTATION_DESC +getLastChar(cName)+"DaoImpl类"+BLANK_1+RT_1
				+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_2
				+"public class " +getLastChar(cName) +"DaoImpl extends CustomBaseSqlDaoImpl implements " +getLastChar(cName) +"DaoCustom  {"+RT_2
				+"    public PageModel<"+getLastChar(cName)+"> query"+getLastChar(cName)+"Page("+getLastChar(cName)+"QueryDTO "+getFirstLowercase(cName)+"QueryDTO){"+RT_1
				+"         Map<String,Object> map = new HashMap<String,Object>();"+RT_1
				+"         StringBuilder hql = new StringBuilder();"+RT_1
				+"         hql.append(\"select t from "+getLastChar(cName)+" t \");"+RT_1
				+"         return this.queryForPageWithParams(hql.toString(),map,"+getFirstLowercase(cName)+"QueryDTO.getCurrentPage(),"+getFirstLowercase(cName)+"QueryDTO.getPageSize());"+RT_1
				+"    }"+RT_2
				+"    public List<"+getLastChar(cName)+"> query"+getLastChar(cName)+"List("+getLastChar(cName)+"QueryDTO "+getFirstLowercase(cName)+"QueryDTO){"+RT_1
				+"         Map<String,Object> map = new HashMap<String,Object>();"+RT_1
				+"         StringBuilder hql = new StringBuilder();"+RT_1
				+"         hql.append(\"select t from "+getLastChar(cName)+" t \");"+RT_1
				+"         return this.queryByMapParams(hql.toString(),map);"+RT_1
				+"    }"+RT_1
				+RT_2+"}");
		fw.flush();
		fw.close();
		showInfo(fileName);
	}else{
		System.out.println("创建DaoImpl接口失败,原因是commonPackage为空!");
	}
}
 
Example 20
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");
}