下面列出了java.io.FileWriter#flush ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void writeJson(String outFileName){
JSONObject obj = new JSONObject();
obj.put("book", "Harry Potter and the Philosopher's Stone");
obj.put("author", "J. K. Rowling");
JSONArray list = new JSONArray();
list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione");
list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.");
list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. ");
obj.put("messages", list);
try {
FileWriter file = new FileWriter(outFileName);
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(obj);
}
/**
* 创建查询信息封装DTO(用于前台的查询信息封装)
* @param c实体类
* @param commonPackage 基础包:如com.jeff.tianti.info
* @param author 作者
* @param desc 描述
* @throws IOException
*/
public static void createFrontQueryDTO(Class c,String commonPackage,String author) throws IOException{
String cName = c.getName();
String dtoPath = "";
if(author == null || author.equals("")){
author = "Administrator";
}
if(commonPackage != null && !commonPackage.equals("")){
dtoPath = commonPackage.replace(".", "/");
String fileName = System.getProperty("user.dir") + "/src/main/java/" + dtoPath+"/dto"
+ "/" + getLastChar(cName) + "FrontQueryDTO.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package "+commonPackage+".dto"+";"+RT_2+"import com.jeff.tianti.common.dto.CommonQueryDTO;"+RT_2
+"/**"+RT_1+BLANK_1+"*"+BLANK_1+ANNOTATION_AUTHOR_PARAMTER+ author +RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DESC +getLastChar(cName)+"QueryDTO"+BLANK_1+RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_1
+"public class " +getLastChar(cName) +"FrontQueryDTO extends CommonQueryDTO{"+RT_2+"}");
fw.flush();
fw.close();
showInfo(fileName);
}else{
System.out.println("创建"+getLastChar(cName)+"FrontQueryDTO失败,原因是commonPackage为空!");
}
}
/**
* 创建Dao接口
* @param c实体类
* @param commonPackage 基础包:如com.jeff.tianti.info
* @param author 作者
* @param desc 描述
* @throws IOException
*/
public static void createDaoInterface(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) + "Dao.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package "+commonPackage+".dao"+";"+RT_2+"import "+commonPackage+".entity"+"."+getLastChar(cName)+";"+RT_1+"import com.jeff.tianti.common.dao.CommonDao;"+RT_2
+"/**"+RT_1+BLANK_1+"*"+BLANK_1+ANNOTATION_AUTHOR_PARAMTER+ author +RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DESC +getLastChar(cName)+"Dao接口"+BLANK_1+RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_1
+"public interface " +getLastChar(cName) +"Dao extends "+getLastChar(cName)+"DaoCustom,CommonDao<"+getLastChar(cName)+",String>{"+RT_2+"}");
fw.flush();
fw.close();
showInfo(fileName);
}else{
System.out.println("创建Dao接口失败,原因是commonPackage为空!");
}
}
@Test
public void testGCPAuthProvider() {
KubeConfig.registerAuthenticator(new GCPAuthenticator());
try {
File config = folder.newFile("config");
FileWriter writer = new FileWriter(config);
writer.write(GCP_CONFIG);
writer.flush();
writer.close();
KubeConfig kc = KubeConfig.loadKubeConfig(new FileReader(config));
assertEquals("fake-token", kc.getAccessToken());
} catch (Exception ex) {
ex.printStackTrace();
fail("Unexpected exception: " + ex);
}
}
/**
* 创建查询信息封装DTO(用于后台的查询信息封装)
* @param c实体类
* @param commonPackage 基础包:如com.jeff.tianti.info
* @param author 作者
* @param desc 描述
* @throws IOException
*/
public static void createQueryDTO(Class c,String commonPackage,String author) throws IOException{
String cName = c.getName();
String dtoPath = "";
if(author == null || author.equals("")){
author = "Administrator";
}
if(commonPackage != null && !commonPackage.equals("")){
dtoPath = commonPackage.replace(".", "/");
String fileName = System.getProperty("user.dir") + "/src/main/java/" + dtoPath+"/dto"
+ "/" + getLastChar(cName) + "QueryDTO.java";
File f = new File(fileName);
FileWriter fw = new FileWriter(f);
fw.write("package "+commonPackage+".dto"+";"+RT_2+"import com.jeff.tianti.common.dto.CommonQueryDTO;"+RT_2
+"/**"+RT_1+BLANK_1+"*"+BLANK_1+ANNOTATION_AUTHOR_PARAMTER+ author +RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DESC +getLastChar(cName)+"QueryDTO"+BLANK_1+RT_1
+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_1
+"public class " +getLastChar(cName) +"QueryDTO extends CommonQueryDTO{"+RT_2+"}");
fw.flush();
fw.close();
showInfo(fileName);
}else{
System.out.println("创建"+getLastChar(cName)+"QueryDTO失败,原因是commonPackage为空!");
}
}
public static synchronized boolean writeContent(File f, String content) {
try {
FileWriter fw = new FileWriter(f);
fw.write(content);
fw.flush();
fw.close();
return true;
} catch (IOException e) {
//TODO Implement Logger
return false;
}
}
public static void toFile(String templateName, VelocityContext ctx, String destPath) {
try {
File file = new File(destPath);
File parentFile = file.getParentFile();
if (parentFile != null && (!parentFile.exists() || (parentFile.exists() && !parentFile.isDirectory()))) {
file.getParentFile().mkdirs();
}
Template template = VelocityKit.getTemplate(templateName);
FileWriter fw = new FileWriter(destPath);
template.merge(ctx, fw);
fw.flush();
} catch (Exception e) {
throw new RuntimeException("生成代码模板时出错:" + e.getMessage());
}
}
public void testLocalInfileDisabled() throws Exception {
createTable("testLocalInfileDisabled", "(field1 varchar(255))");
File infile = File.createTempFile("foo", "txt");
infile.deleteOnExit();
//String url = infile.toURL().toExternalForm();
FileWriter output = new FileWriter(infile);
output.write("Test");
output.flush();
output.close();
Connection loadConn = getConnectionWithProps(new Properties());
try {
// have to do this after connect, otherwise it's the server that's enforcing it
((com.mysql.jdbc.Connection) loadConn).setAllowLoadLocalInfile(false);
try {
loadConn.createStatement().execute("LOAD DATA LOCAL INFILE '" + infile.getCanonicalPath() + "' INTO TABLE testLocalInfileDisabled");
fail("Should've thrown an exception.");
} catch (SQLException sqlEx) {
assertEquals(SQLError.SQL_STATE_GENERAL_ERROR, sqlEx.getSQLState());
}
assertFalse(loadConn.createStatement().executeQuery("SELECT * FROM testLocalInfileDisabled").next());
} finally {
loadConn.close();
}
}
public void writeConfigFile(Context context) throws IOException {
FileWriter cfg = new FileWriter(VPNLaunchHelper.getConfigFilePath(context));
cfg.write(getConfigFile(context, false));
cfg.flush();
cfg.close();
}
private void serializeConnectionParams(){
try{
logger.info("Seralizing drivers to file "+new File(fileName).getAbsolutePath());
ObjectMapper objectMapper = new ObjectMapper();
String dataToRight = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(connParams);
FileWriter writer = new FileWriter(fileName);
writer.write(dataToRight);
writer.flush();
writer.close();
}catch(Exception e){
logger.error("Unable to seralize connection manager ",e);
}
}
/**
* 输出JSON到文件
*
* @param file 文件
* @param content 内容
* @throws IOException
*/
private void writeFile(File file, String content) throws IOException {
FileWriter writer = new FileWriter(file);
try {
writer.write(content);
writer.flush();
} finally {
Close.close(writer);
}
}
public static Object newProxyInstance(MyClassLoader classLoader, Class<?> [] interfaces, MyInvocationHandler h){
try {
//1、动态生成源代码.java文件
String src = generateSrc(interfaces);
//2、Java文件输出磁盘
String filePath = MyProxy.class.getResource("").getPath();
System.out.println(filePath);
File f = new File(filePath + "$Proxy0.java");
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//3、把生成的.java文件编译成.class文件
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manage = compiler.getStandardFileManager(null,null,null);
Iterable iterable = manage.getJavaFileObjects(f);
JavaCompiler.CompilationTask task = compiler.getTask(null,manage,null,null,null,iterable);
task.call();
manage.close();
//4、编译生成的.class文件加载到JVM中来
Class proxyClass = classLoader.findClass("$Proxy0");
Constructor c = proxyClass.getConstructor(MyInvocationHandler.class);
f.delete();
//5、返回字节码重组以后的新的代理对象
return c.newInstance(h);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
OnThrowTest myTest = new OnThrowTest();
String launch = System.getProperty("test.classes") +
File.separator + "OnThrowLaunch.sh";
File f = new File(launch);
f.delete();
FileWriter fw = new FileWriter(f);
fw.write("#!/bin/sh\n echo OK $* > " +
myTest.touchFile.replace('\\','/') + "\n exit 0\n");
fw.flush();
fw.close();
if ( ! f.exists() ) {
throw new Exception("Test failed: sh file not created: " + launch);
}
String javaExe = System.getProperty("java.home") +
File.separator + "bin" + File.separator + "java";
String targetClass = "OnThrowTarget";
String cmds [] = {javaExe,
"-agentlib:jdwp=transport=dt_socket," +
"onthrow=OnThrowException,server=y,suspend=n," +
"launch=" + "sh " + launch.replace('\\','/'),
targetClass};
/* Run the target app, which will launch the launch script */
myTest.run(cmds);
if ( !myTest.touchFileExists() ) {
throw new Exception("Test failed: touch file not found: " +
myTest.touchFile);
}
System.out.println("Test passed: launch create file");
}
/**
* 将内容写入文件
* @param fileContent 内容
* @param fileName 文件名
*/
private static void writeContentToFile(StringBuilder fileContent, String fileName) throws IOException {
FileWriter writer = new FileWriter(fileName);
writer.write(fileContent.toString());
writer.flush();
writer.close();
}
public void testLocalInfileDisabled() throws Exception {
createTable("testLocalInfileDisabled", "(field1 varchar(255))");
File infile = File.createTempFile("foo", "txt");
infile.deleteOnExit();
//String url = infile.toURL().toExternalForm();
FileWriter output = new FileWriter(infile);
output.write("Test");
output.flush();
output.close();
Connection loadConn = getConnectionWithProps(new Properties());
try {
// have to do this after connect, otherwise it's the server that's enforcing it
((com.mysql.jdbc.Connection) loadConn).setAllowLoadLocalInfile(false);
try {
loadConn.createStatement().execute("LOAD DATA LOCAL INFILE '" + infile.getCanonicalPath() + "' INTO TABLE testLocalInfileDisabled");
fail("Should've thrown an exception.");
} catch (SQLException sqlEx) {
assertEquals(SQLError.SQL_STATE_GENERAL_ERROR, sqlEx.getSQLState());
}
assertFalse(loadConn.createStatement().executeQuery("SELECT * FROM testLocalInfileDisabled").next());
} finally {
loadConn.close();
}
}
public static void main(String[] args) throws Exception {
OnThrowTest myTest = new OnThrowTest();
String launch = System.getProperty("test.classes") +
File.separator + "OnThrowLaunch.sh";
File f = new File(launch);
f.delete();
FileWriter fw = new FileWriter(f);
fw.write("#!/bin/sh\n echo OK $* > " +
myTest.touchFile.replace('\\','/') + "\n exit 0\n");
fw.flush();
fw.close();
if ( ! f.exists() ) {
throw new Exception("Test failed: sh file not created: " + launch);
}
String javaExe = System.getProperty("java.home") +
File.separator + "bin" + File.separator + "java";
String targetClass = "OnThrowTarget";
String cmds [] = {javaExe,
"-agentlib:jdwp=transport=dt_socket," +
"onthrow=OnThrowException,server=y,suspend=n," +
"launch=" + "sh " + launch.replace('\\','/'),
targetClass};
/* Run the target app, which will launch the launch script */
myTest.run(cmds);
if ( !myTest.touchFileExists() ) {
throw new Exception("Test failed: touch file not found: " +
myTest.touchFile);
}
System.out.println("Test passed: launch create file");
}
/**
* constructor.
*/
public static void clearInfoForFile(String fileName) {
File file = new File(fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@BeforeClass
public static void setup() throws Exception {
skipIfHadoopVersionIsNotAppropriate();
LOG.info("starting secure cluster environment for testing");
dataDir = tempFolder.newFolder();
conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, dataDir.getAbsolutePath());
SecureTestEnvironment.prepare(tempFolder);
populateSecureConfigurations();
Configuration flinkConfig = new Configuration();
flinkConfig.setString(SecurityOptions.KERBEROS_LOGIN_KEYTAB,
SecureTestEnvironment.getTestKeytab());
flinkConfig.setString(SecurityOptions.KERBEROS_LOGIN_PRINCIPAL,
SecureTestEnvironment.getHadoopServicePrincipal());
SecurityConfiguration ctx =
new SecurityConfiguration(
flinkConfig,
Collections.singletonList(securityConfig -> new HadoopModule(securityConfig, conf)));
try {
TestingSecurityContext.install(ctx, SecureTestEnvironment.getClientSecurityConfigurationMap());
} catch (Exception e) {
throw new RuntimeException("Exception occurred while setting up secure test context. Reason: {}", e);
}
File hdfsSiteXML = new File(dataDir.getAbsolutePath() + "/hdfs-site.xml");
FileWriter writer = new FileWriter(hdfsSiteXML);
conf.writeXml(writer);
writer.flush();
writer.close();
Map<String, String> map = new HashMap<String, String>(System.getenv());
map.put("HADOOP_CONF_DIR", hdfsSiteXML.getParentFile().getAbsolutePath());
TestBaseUtils.setEnv(map);
MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
builder.checkDataNodeAddrConfig(true);
builder.checkDataNodeHostConfig(true);
hdfsCluster = builder.build();
dfs = hdfsCluster.getFileSystem();
hdfsURI = "hdfs://"
+ NetUtils.hostAndPortToUrlString(hdfsCluster.getURI().getHost(), hdfsCluster.getNameNodePort())
+ "/";
Configuration configuration = startSecureFlinkClusterWithRecoveryModeEnabled();
miniClusterResource = new MiniClusterResource(
new MiniClusterResourceConfiguration.Builder()
.setConfiguration(configuration)
.setNumberTaskManagers(1)
.setNumberSlotsPerTaskManager(4)
.build());
miniClusterResource.before();
}
private Response exportCsv(Report toExport, Set<ReportParameter> reportParams) {
try {
File file = new File(DashboardConstants.APPLN_TEMP_DIR+System.nanoTime());
logger.info("Export CSV temp file path is "+file.getAbsoluteFile());
FileWriter writer = new FileWriter(file);
writer.write("Report : "+toExport.getTitle()+"\n");
List<RowElement> rows = toExport.getRows();
for (RowElement rowElement : rows) {
List<Element> elements = rowElement.getElements();
for (Element element : elements) {
writer.write("\nElement : "+element.getTitle()+"\n");
try {
element.setParams(reportParams);
element.init();
List<List<Object>> data = element.getData();
for (List<Object> row : data) {
StringBuffer toWrite = new StringBuffer();
for (Object cell : row) {
toWrite.append(cell.toString()+",");
}
writer.write(toWrite.toString()+"\n");
}
} catch (Exception e) {
logger.error("Unable to init '"+element.getTitle()+"' element of report '"+toExport.getTitle()+"' Error "+e.getMessage(),e);
return Response.serverError().entity("Unable to init '"+element.getTitle()+"' element of report '"+toExport.getTitle()+"' Error "+e.getMessage()).build();
}
}
}
writer.flush();
writer.close();
ResponseBuilder responseBuilder = Response.ok((Object) file);
responseBuilder.header("Access-Control-Allow-Origin","*");
responseBuilder.header("Content-Type", "text/csv");
responseBuilder.header("Content-Disposition", "attachment;filename="+file.getName()+".csv");
responseBuilder.header("Content-Length", file.length());
Response responseToSend = responseBuilder.build();
file.deleteOnExit();
return responseToSend;
} catch (IOException e1) {
logger.error("Unable to export '"+toExport.getTitle()+"' report ",e1);
return Response.serverError().entity("Unable to export '"+toExport.getTitle()+"' report "+e1.getMessage()).build();
}
}
public void writeConfigFile(Context context) throws IOException {
FileWriter cfg = new FileWriter(VPNLaunchHelper.getConfigFilePath(context));
cfg.write(getConfigFile(context, false));
cfg.flush();
cfg.close();
}