下面列出了java.io.FileWriter#write ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
}
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");
}
}
@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();
}
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));
}
}
}
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");
}
}
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;
}
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("保存失败");
}
}
/** 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(); }
}
@Override
public void onResponse() throws Exception {
if(file.exists()) {
file.delete();
}
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(output);
writer.close();
}
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();
}
}
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;
}
@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"));
}
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;
}
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);
}
//
}
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();
}
}
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();
}
}
private void makeNonEmptyFile(File file, String contents)
throws IOException {
FileWriter fw = new FileWriter(file);
fw.write(contents);
fw.close();
}
@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);
}
/**
* 创建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为空!");
}
}
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");
}