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

The following are Jave code examples for showing how to use flush() 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: 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 2
Project: tianti   File: GenCodeUtil.java   View Source Code Vote up 6 votes
/**
 * 创建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为空!");
	}
}
 
Example 3
Project: easy-test   File: FindNotMakeTest.java   View Source Code Vote up 6 votes
private void logInfo(String msg) {
    if (logPath == null) {
        logger.info(msg);
    } else {
        try {
            FileUtils.createFile(logPath);
            // WTF windows
            FileWriter fw = new FileWriter(logPath, true);
            fw.write(msg);
            fw.write("\n");
            fw.flush();
            fw.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example 4
Project: PokerBankroll   File: Funcoes.java   View Source Code Vote up 5 votes
public static File saveFile(Context context, String filename, String dados) {

        if (!isExternalStorageWritable())
            Toast.makeText(context, context.getString(R.string.n_001), Toast.LENGTH_LONG).show();

        if (isExternalStorageReadable()) {
            Toast.makeText(context, context.getString(R.string.n_001), Toast.LENGTH_LONG).show();
        }

        try {
            File root = new File(Environment.getExternalStorageDirectory(), context.getString(context.getApplicationInfo().labelRes));
            if (!root.exists())
                //noinspection ResultOfMethodCallIgnored
                root.mkdirs();

            File sFile = new File(root, filename);
            if (sFile.exists())
                //noinspection ResultOfMethodCallIgnored
                sFile.delete();

            FileWriter writer = new FileWriter(sFile);
            writer.append(dados);
            writer.flush();
            writer.close();

            return sFile;
        } catch (IOException e) {
            Toast.makeText(context, context.getString(R.string.n_001), Toast.LENGTH_LONG).show();
        }

        return null;
    }
 
Example 5
Project: tianti   File: GenCodeUtil.java   View Source Code Vote up 5 votes
/**
 * 创建DaoCustom接口
 * @param c实体类
 * @param commonPackage 基础包:如com.jeff.tianti.info
 * @throws IOException
 */
public static void createDaoCustomInterface(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) + "DaoCustom.java";
		File f = new File(fileName);
		FileWriter fw = new FileWriter(f);
		fw.write("package "+commonPackage+".dao"+";"+RT_2
				+"import com.jeff.tianti.common.entity.PageModel;"+RT_1
				+"import java.util.List;"+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)+"DaoCustom接口"+BLANK_1+RT_1
				+BLANK_1+"*"+BLANK_1+ANNOTATION_DATE +getDate()+RT_1+BLANK_1+"*/"+RT_1
				+"public interface " +getLastChar(cName) +"DaoCustom {"+RT_2
				+"      PageModel<"+getLastChar(cName)+"> query"+getLastChar(cName)+"Page("+getLastChar(cName)+"QueryDTO "+getFirstLowercase(cName)+"QueryDTO);"+RT_2
				+"      List<"+getLastChar(cName)+"> query"+getLastChar(cName)+"List("+getLastChar(cName)+"QueryDTO "+getFirstLowercase(cName)+"QueryDTO);"+RT_2
				+RT_2+"}");
		fw.flush();
		fw.close();
		showInfo(fileName);
	}else{
		System.out.println("创建DaoCustom接口失败,原因是commonPackage为空!");
	}
	
}
 
Example 6
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 7
Project: fuck_zookeeper   File: ZooKeeperServerMainTest.java   View Source Code Vote up 5 votes
public MainThread(int clientPort, boolean preCreateDirs) throws IOException {
    super("Standalone server with clientPort:" + clientPort);
    tmpDir = ClientBase.createTmpDir();
    confFile = new File(tmpDir, "zoo.cfg");

    FileWriter fwriter = new FileWriter(confFile);
    fwriter.write("tickTime=2000\n");
    fwriter.write("initLimit=10\n");
    fwriter.write("syncLimit=5\n");

    File dataDir = new File(tmpDir, "data");
    String dir = dataDir.toString();
    String dirLog = dataDir.toString() + "_txnlog";
    if (preCreateDirs) {
        if (!dataDir.mkdir()) {
            throw new IOException("unable to mkdir " + dataDir);
        }
        dirLog = dataDir.toString();
    }
    
    // Convert windows path to UNIX to avoid problems with "\"
    String osname = java.lang.System.getProperty("os.name");
    if (osname.toLowerCase().contains("windows")) {
        dir = dir.replace('\\', '/');
        dirLog = dirLog.replace('\\', '/');
    }
    fwriter.write("dataDir=" + dir + "\n");
    fwriter.write("dataLogDir=" + dirLog + "\n");
    fwriter.write("clientPort=" + clientPort + "\n");
    fwriter.flush();
    fwriter.close();

    main = new TestZKSMain();
}
 
Example 8
Project: boohee_v5.6   File: LOG.java   View Source Code Vote up 5 votes
public static synchronized void logMessage(List<String> list) {
    synchronized (LOG.class) {
        if (!(CommonUtils.isBlank(b) || CommonUtils.isBlank(c))) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(c);
            for (String str : list) {
                stringBuffer.append(", " + str);
            }
            stringBuffer.append("\n");
            try {
                File file = new File(a);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File file2 = new File(a, b);
                if (!file2.exists()) {
                    file2.createNewFile();
                }
                FileWriter fileWriter = file2.length() + ((long) stringBuffer.length()) <= 51200 ? new FileWriter(file2, true) : new FileWriter(file2);
                fileWriter.write(stringBuffer.toString());
                fileWriter.flush();
                fileWriter.close();
            } catch (Exception e) {
                e.toString();
            }
        }
    }
}
 
Example 9
Project: Daedalus   File: Configurations.java   View Source Code Vote up 5 votes
public void save() {
    try {
        if (file != null) {
            FileWriter writer = new FileWriter(file);
            new Gson().toJson(this, writer);
            writer.flush();
            writer.close();
        }
    } catch (IOException e) {
        Logger.logException(e);
    }
}
 
Example 10
Project: BibliotecaPS   File: ConnectionTest.java   View Source Code Vote up 5 votes
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();
    }
}
 
Example 11
Project: uavstack   File: Log4jTest.java   View Source Code Vote up 5 votes
public void writeStackTrace() throws IOException, InterruptedException {
    // used in window
    // File expectOutput = new File("D:\\logFolder\\expectOutput.txt");
    // FileWriter writerExpect = new FileWriter(expectOutput,true);

    // used in linux
    File expectOutput = new File("/home/work/UAV/Log/expectOutput.txt");
    @SuppressWarnings("resource")
    FileWriter writerExpect = new FileWriter(expectOutput, true);

    Thread.sleep(10000);
    logger.error("IOexception", new IOException("1111111111 failed.."));
    System.out.println(" IOexception >>>>  111111111");
    writerExpect.write(
            "{\"stacktrace\":\"java.io.IOException: 1111111111 failed..\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:191)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    Thread.sleep(10000);
    logger.error("InterruptedException", new InterruptedException("222222222 faild.."));
    System.out.println("InterruptedException >>> 222222222");
    writerExpect.write(
            "{\"stacktrace\":\"java.lang.InterruptedException: 222222222 faild..\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:197)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    Thread.sleep(10000);
    logger.error("ClassNotFoundException", new ClassNotFoundException("33333333"));
    System.out.println("ClassNotFoundException >>> 33333333");
    writerExpect.write(
            "{\"stacktrace\":\"java.lang.ClassNotFoundException: 33333333\\tat com.creditease.monitorframework.fat.Log4jTest.writeStackTrace(Log4jTest.java:203)\\tat com.creditease.monitorframework.fat.Log4jTest.doGet(Log4jTest.java:48)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:624)\\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:731)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:307)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)\\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:245)\\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:212)\\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)\\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)\\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)\\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)\\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)\\tat org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)\\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)\\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:443)\\tat org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)\\tat org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)\\tat org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)\\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)\\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)\\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\\tat java.lang.Thread.run(Thread.java:745)\"}\r\n");
    writerExpect.flush();

    System.out.println("*********** the end of stack trace *********");

}
 
Example 12
Project: sumo   File: GenericCSVIO.java   View Source Code Vote up 5 votes
public static void createSimpleCSV(GeometryImage glayer, String file,boolean append) throws IOException {
FileWriter fw = new FileWriter(file,append);
try{
       if(!append)
       	fw.append("geom," + glayer.getSchema(',') + "\n");
       WKTWriter wkt = new WKTWriter();
       for (Geometry geom : glayer.getGeometries()) {
           fw.append("\"" + wkt.writeFormatted(geom) + "\",");
           AttributesGeometry att = glayer.getAttributes(geom);
           if (att == null || att.getSchema().length==0) {
               fw.append("\n");
               continue;
           }
           for (int i = 0; i < att.getSchema().length; i++) {
               String key = att.getSchema()[i];
               fw.append(att.get(key) + "");
               if (i < att.getSchema().length - 1) {
                   fw.append(",");
               } else {
                   fw.append("\n");
               }
           }
       }
}finally{    
	fw.flush();
	fw.close();
}	
  }
 
Example 13
Project: hadoop   File: TestCombineFileRecordReader.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
@Test
public void testProgressIsReportedIfInputASeriesOfEmptyFiles() throws IOException, InterruptedException {
  JobConf conf = new JobConf();
  Path[] paths = new Path[3];
  File[] files = new File[3];
  long[] fileLength = new long[3];

  try {
    for(int i=0;i<3;i++){
      File dir = new File(outDir.toString());
      dir.mkdir();
      files[i] = new File(dir,"testfile"+i);
      FileWriter fileWriter = new FileWriter(files[i]);
      fileWriter.flush();
      fileWriter.close();
      fileLength[i] = i;
      paths[i] = new Path(outDir+"/testfile"+i);
    }

    CombineFileSplit combineFileSplit = new CombineFileSplit(paths, fileLength);
    TaskAttemptID taskAttemptID = Mockito.mock(TaskAttemptID.class);
    TaskReporter reporter = Mockito.mock(TaskReporter.class);
    TaskAttemptContextImpl taskAttemptContext =
      new TaskAttemptContextImpl(conf, taskAttemptID,reporter);

    CombineFileRecordReader cfrr = new CombineFileRecordReader(combineFileSplit,
      taskAttemptContext, TextRecordReaderWrapper.class);

    cfrr.initialize(combineFileSplit,taskAttemptContext);

    verify(reporter).progress();
    Assert.assertFalse(cfrr.nextKeyValue());
    verify(reporter, times(3)).progress();
  } finally {
    FileUtil.fullyDelete(new File(outDir.toString()));
  }
}
 
Example 14
Project: Patterdale   File: ConfigUnmarshallerTest.java   View Source Code Vote up 5 votes
@Test
public void blowsUpIfPassWordsFileIsMalformed() throws Exception {
    File tempFile = temporaryFolder.newFile("patterdale.yml");
    FileWriter fileWriter = new FileWriter(tempFile);
    fileWriter.write("invalid content");
    fileWriter.flush();

    assertThatThrownBy(() -> configUnmarshaller.parseConfig(tempFile))
            .isExactlyInstanceOf(IllegalArgumentException.class)
            .hasMessage(format("Error occurred reading config file '%s'.", tempFile.getName()))
            .hasCauseExactlyInstanceOf(JsonMappingException.class);
}
 
Example 15
Project: monarch   File: FileProcessControllerIntegrationJUnitTest.java   View Source Code Vote up 4 votes
private static void writeToFile(final File file, final String value) throws IOException {
  final FileWriter writer = new FileWriter(file);
  writer.write(value);
  writer.flush();
  writer.close();
}
 
Example 16
Project: elasticbak   File: BackupEsIndex.java   View Source Code Vote up 4 votes
/**
 * 备份索引settings
 * 
 * @param client
 * @param indexname
 * @param file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ExecutionException
 * @throws InterruptedException
 */
public void backupIdxMeta() throws FileNotFoundException, IOException, InterruptedException, ExecutionException {

	logmsg = new HashMap<String, Object>();
	// 获取index settings
	ClusterState cs = backup.getClient().admin().cluster().prepareState().setIndices(backup.getIndexname())
			.execute().actionGet().getState();
	IndexMetaData imd = cs.getMetaData().index(backup.getIndexname());
	IndexMeta indexmeta = new IndexMeta();

	Settings settings = imd.getSettings();

	Map<String, String> set = settings.getAsMap();
	indexmeta.setIdxsetting(set);

	// 获取index mapping
	Map<String, Object> mapping = new HashMap<String, Object>();
	GetMappingsResponse res = backup.getClient().admin().indices()
			.getMappings(new GetMappingsRequest().indices(backup.getIndexname())).get();
	ImmutableOpenMap<String, MappingMetaData> idxmapping = res.mappings().get(backup.getIndexname());
	for (ObjectObjectCursor<String, MappingMetaData> c : idxmapping) {
		mapping.put(c.key, c.value.getSourceAsMap());
	}
	indexmeta.setIdxmapping(mapping);

	// 序列化对象到文件
	if (!backup.getBackuppath().endsWith(File.separator)) {
		backup.setBackuppath(backup.getBackuppath() + File.separator);
	}

	if (0 == backup.getBackuppath().indexOf("./")) {
		backup.setBackuppath(backup.getBackuppath().replace("./", ""));
	}

	// IndexMetaData 转 json
	ObjectMapper mapper = new ObjectMapper();
	String indexmetajson = mapper.writeValueAsString(indexmeta);

	// 写入文件
	String filename = backup.getBackuppath() + backup.getIndexname() + ".meta";
	FileWriter fw = new FileWriter(filename);
	fw.write(indexmetajson);
	fw.flush();
	fw.close();

	// 写日志
	logmsg.put("Action", "backup index meta");
	logmsg.put("Index", backup.getIndexname());
	logmsg.put("backupfile", new File(backup.getBackuppath() + backup.getIndexname() + ".meta").getAbsolutePath());
	logger.info(jsonutil.MapToJson(logmsg));
}
 
Example 17
Project: lembredio   File: FarmaceuticoInterface.java   View Source Code Vote up 4 votes
private void ButtonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonSalvarActionPerformed
    File diretorio = new File("EstoqueFarmacias");
    diretorio.mkdir();
    File Estoque = new File(diretorio,nomeFarmacia + ".txt");

    try {
        FileWriter fw = new FileWriter(Estoque, true);
        if(TextFieldNomeReme.getText().length()>0 && FormattedFieldQuantReme.getText().length() > 0 && FormattedTextFieldPU.getText().length() > 0){
            fw.write(TextFieldNomeReme.getText());
            fw.write("\r\n");
            fw.write(FormattedFieldQuantReme.getText());
            fw.write("\r\n");
            fw.write(FormattedTextFieldPU.getText());
            fw.write("\r\n");
            
            fw.flush();
            fw.close();
            
            JOptionPane.showMessageDialog(null,"Remédio Cadastrado com sucesso!");
            
            TextFieldNomeReme.setText("");
            FormattedFieldQuantReme.setText("");
            FormattedTextFieldPU.setText("");
            
        }
        else if(TextFieldNomeReme.getText().length()<=0 || FormattedFieldQuantReme.getText().length() <= 0 || FormattedTextFieldPU.getText().length() <= 0){
            if(TextFieldNomeReme.getText().length()<= 0){
                JOptionPane.showMessageDialog(null,"Entre com o nome do remédio!");
            }
            if (FormattedFieldQuantReme.getText().length() <= 0){
                JOptionPane.showMessageDialog(null,"Entre com a quantidade de remédios!");
            }
            else{
                JOptionPane.showMessageDialog(null,"Entre com o preço!!");
            }
        }
      

    } catch (IOException ex) {
        Logger.getLogger(FarmaceuticoInterface.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 18
Project: tianti   File: GenCodeUtil.java   View Source Code Vote up 4 votes
/**
 * 创建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 19
Project: Spark   File: NetProcessor.java   View Source Code Vote up 4 votes
private final void processTimestamp(String line)
{
	StringTokenizer st = new StringTokenizer(line);
	st.nextToken();

	long timestamp = Long.parseLong(st.nextToken());
	long epoch = Long.parseLong(st.nextToken());

	if (localPlayer.timestampLastTick != 0
			&& localPlayer.timestampLastEpoch != 0)
	{
		long EpochDifference = Math.abs(epoch
				- localPlayer.timestampLastEpoch);
		long TickDifference = Math.abs(timestamp
				- localPlayer.timestampLastTick);
		if ((TickDifference - EpochDifference) > 1000)
		{
			String CheatString = server.dateFormatting.dateFormatMinute
					.format(new Date())
					+ " - "
					+ localPlayer.Name
					+ " was detected speedhacking.  Epoch: "
					+ EpochDifference + "   Tick: " + TickDifference;
			System.err.println(CheatString);
			try
			{
				FileWriter fw = new FileWriter("CheatLog.txt", true);
				fw.write(CheatString + "\r\n");
				fw.flush();
				fw.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		localPlayer.timestampLastEpoch = epoch;
		localPlayer.timestampLastTick = timestamp;
	}
	else
	{
		localPlayer.timestampLastTick = timestamp;
		localPlayer.timestampLastEpoch = epoch;
	}
}
 
Example 20
Project: TrabalhoFinalEDA2   File: mxUtils.java   View Source Code Vote up 3 votes
/**
 * Writes the given string into the given file.
 * 
 * @param contents
 *            String representing the file contents.
 * @param filename
 *            Name of the file to be written.
 * @throws IOException
 */
public static void writeFile(String contents, String filename)
		throws IOException
{
	FileWriter fw = new FileWriter(filename);
	fw.write(contents);
	fw.flush();
	fw.close();
}