当前位置: 首页>>代码示例>>Java>>正文


Java PrintWriter类代码示例

本文整理汇总了Java中java.io.PrintWriter的典型用法代码示例。如果您正苦于以下问题:Java PrintWriter类的具体用法?Java PrintWriter怎么用?Java PrintWriter使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


PrintWriter类属于java.io包,在下文中一共展示了PrintWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: onPreHandle

import java.io.PrintWriter; //导入依赖的package包/类
@Override
public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
    if (this.isAccessAllowed(request, response, mappedValue) && this.isLoginRequest(request, response)) {
        if (((HttpServletRequest)request).getRequestURL().toString().endsWith(".json")){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println("{\"code\":200,\"info\":\"already logined\"}");
            out.flush();
            out.close();
        }else {
            WebUtils.issueRedirect(request,response,this.getSuccessUrl());
        }
        return false;
    }
    return super.onPreHandle(request, response, mappedValue);
}
 
开发者ID:liaojiacan,项目名称:zkAdmin,代码行数:18,代码来源:LoginFilter.java

示例2: main

import java.io.PrintWriter; //导入依赖的package包/类
public static void main(String argv[]) throws Exception {
    AutoRunFromConsole.runYourselfInConsole(true);
    String clientSentence;
    ServerSocket welcomeSocket = new ServerSocket(4405);
    System.out.println("Logger started!");
    PrintWriter outPrinter = new PrintWriter("tcp_log.txt");
    while (true) {
      
        Socket connectionSocket = welcomeSocket.accept();
        BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
        while (true) {
            try {
                clientSentence = inFromClient.readLine();
                if (clientSentence == null) break;
                System.out.println(clientSentence);
                outPrinter.println(clientSentence);
                outPrinter.flush();
            } catch (Exception e) {
                break;
            }                
        }
        
        System.out.println("Connection closed.");
    }
}
 
开发者ID:Maschell,项目名称:nn_nex_logging_and_research,代码行数:26,代码来源:TCPServer.java

示例3: format

import java.io.PrintWriter; //导入依赖的package包/类
private synchronized String format(Level level, String msg, Throwable thrown) {
    date.setTime(System.currentTimeMillis());
    String throwable = "";
    if (thrown != null) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        pw.println();
        thrown.printStackTrace(pw);
        pw.close();
        throwable = sw.toString();
    }

    return String.format(formatString,
                         date,
                         getCallerInfo(),
                         name,
                         level.name(),
                         msg,
                         throwable);
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:21,代码来源:PlatformLogger.java

示例4: isClassOk

import java.io.PrintWriter; //导入依赖的package包/类
/**
 * Check to see if a class is well-formed.
 *
 * @param logger the logger to write to if a problem is found
 * @param logTag a tag to print to the log if a problem is found
 * @param classNode the class to check
 * @return true if the class is ok, false otherwise
 */
public static boolean isClassOk(final Logger logger, final String logTag, final ClassNode classNode) {
  final StringWriter sw = new StringWriter();
  final ClassWriter verifyWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
  classNode.accept(verifyWriter);
  final ClassReader ver = new ClassReader(verifyWriter.toByteArray());
  try {
    DrillCheckClassAdapter.verify(ver, false, new PrintWriter(sw));
  } catch(final Exception e) {
    logger.info("Caught exception verifying class:");
    logClass(logger, logTag, classNode);
    throw e;
  }
  final String output = sw.toString();
  if (!output.isEmpty()) {
    logger.info("Invalid class:\n" +  output);
    return false;
  }

  return true;
}
 
开发者ID:skhalifa,项目名称:QDrill,代码行数:29,代码来源:AsmUtil.java

示例5: createFile

import java.io.PrintWriter; //导入依赖的package包/类
private static FileObject createFile (
        final FileObject root,
        final String fqn,
        final String content) throws IOException {
    final FileObject file = FileUtil.createData(
            root,
            String.format("%s.java", fqn.replace('.', '/'))); //NOI18N
    final FileLock lck = file.lock();
    try {
        final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck)));
        try {
            out.print(content);
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    return file;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:21,代码来源:WhiteListSupportTest.java

示例6: helpScreen

import java.io.PrintWriter; //导入依赖的package包/类
public String helpScreen() {
    StringBuffer usage = new StringBuffer();
    HelpFormatter formatter = new HelpFormatter();

    if (cliOrder != null && cliOrder.size() > 0) {
        formatter.setOptionComparator(new OptionComparator());
    }

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    formatter.printHelp(pw,
                        HCPMoverProperties.CLI_WIDTH.getAsInt(),
                        getHelpUsageLine(),
                        null /* header */,
                        getOptions(),
                        HelpFormatter.DEFAULT_LEFT_PAD /* leftPad */,
                        HelpFormatter.DEFAULT_DESC_PAD /* descPad */,
                        null /* footer */,
                        false /* autoUsage */
    );

    usage.append(getHelpHeader());
    usage.append(sw.toString());
    usage.append(getHelpFooter());
    return usage.toString();
}
 
开发者ID:Hitachi-Data-Systems,项目名称:Open-DM,代码行数:27,代码来源:AbstractArcCli.java

示例7: saveLogFile

import java.io.PrintWriter; //导入依赖的package包/类
/**
 * Saves the state of the logger to a file.
 * @throws IOException 
 */
@Override
public void saveLogFile() throws IOException {
    File logFile = new File(this.filename);
    if ( !(logFile.exists()) )
        logFile.createNewFile();
    
    FileWriter fileWriter = new FileWriter(this.filename);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    
    printWriter.println("id,x,y,z");
    
    for(int ctr = 0; ctr < this.ids.size(); ctr++) {
        printWriter.printf(
            "%d,%.4f,%.4f,%.4f%n",
            this.ids.get(ctr),
            this.x.get(ctr),
            this.y.get(ctr),
            this.z.get(ctr)
        );
    }
    
    printWriter.close();
}
 
开发者ID:LEB-EPFL,项目名称:SASS,代码行数:28,代码来源:PositionLogger.java

示例8: main

import java.io.PrintWriter; //导入依赖的package包/类
public static void main(String[] args) throws IOException {
    PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
    Byte b = 1;
    int c;
    while ((c = System.in.read()) != -1) {
        char ch = (char) c;
        if (b == 1) {
            if (ch >= 'a' && ch <= 'z') ch = ((char) ((int) ch - 32));
            if (ch >= 'A' && ch <= 'Z') b = 0;
        } else {
            if (ch >= 'A' && ch <= 'Z') ch = (char) ((int) ch + 32);
        }
        if (ch == '.' || ch == '!' || ch == '?') b = 1;
        out.print(ch);
    }
    out.flush();
}
 
开发者ID:bakhodirsbox,项目名称:AlgoCS,代码行数:18,代码来源:AntiCAPS_1601.java

示例9: execute

import java.io.PrintWriter; //导入依赖的package包/类
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/package-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
开发者ID:youseries,项目名称:urule,代码行数:17,代码来源:PackageServletHandler.java

示例10: createSource

import java.io.PrintWriter; //导入依赖的package包/类
private FileObject createSource(
        @NonNull final FileObject root,
        @NonNull final String fqn,
        @NonNull final String content) throws IOException {
    final FileObject file = FileUtil.createData(root, fqn.replace('.', '/')+"."+JavaDataLoader.JAVA_EXTENSION);   //NOI18N
    final FileLock lck = file.lock();
    try {
        final PrintWriter out = new PrintWriter(new OutputStreamWriter(file.getOutputStream(lck),"UTF-8"));    //NOI18N
        try {
            out.print(content);
        } finally {
            out.close();
        }
    } finally {
        lck.releaseLock();
    }
    return file;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:ReferencesCountTest.java

示例11: dumpSessions

import java.io.PrintWriter; //导入依赖的package包/类
synchronized public void dumpSessions(PrintWriter pwriter) {
    pwriter.print("Session Sets (");
    pwriter.print(sessionSets.size());
    pwriter.println("):");
    ArrayList<Long> keys = new ArrayList<Long>(sessionSets.keySet());
    Collections.sort(keys);
    for (long time : keys) {
        pwriter.print(sessionSets.get(time).sessions.size());
        pwriter.print(" expire at ");
        pwriter.print(new Date(time));
        pwriter.println(":");
        for (SessionImpl s : sessionSets.get(time).sessions) {
            pwriter.print("\t0x");
            pwriter.println(Long.toHexString(s.sessionId));
        }
    }
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:18,代码来源:SessionTrackerImpl.java

示例12: runAndCheck

import java.io.PrintWriter; //导入依赖的package包/类
public RedisProcess runAndCheck() throws IOException, InterruptedException, FailedToStartRedisException {
    List<String> args = new ArrayList(options.values());
    if (sentinelFile != null && sentinelFile.length() > 0) {
        String confFile = defaultDir + File.separator + sentinelFile;
        try (PrintWriter printer = new PrintWriter(new FileWriter(confFile))) {
            args.stream().forEach((arg) -> {
                if (arg.contains("--")) {
                    printer.println(arg.replace("--", "\n\r"));
                }
            });
        }
        args = args.subList(0, 1);
        args.add(confFile);
        args.add("--sentinel");
    }
    RedisProcess rp = runWithOptions(this, args.toArray(new String[0]));
    if (!isCluster()
            && rp.redisProcess.waitFor(1000, TimeUnit.MILLISECONDS)) {
        throw new FailedToStartRedisException();
    }
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        rp.stop();
    }));
    return rp;
}
 
开发者ID:qq1588518,项目名称:JRediClients,代码行数:26,代码来源:RedisRunner.java

示例13: addFavorite

import java.io.PrintWriter; //导入依赖的package包/类
public static void addFavorite(String ip, int port) throws IOException
{
	try
	{
		String path = Runner.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		PrintWriter pw = new PrintWriter(new FileWriter(path + "favorites.ini", true));
		if (!favorites.contains(ip + " " + port))
		{
			System.out.println("You haven't visited this server before. Would you like to save it for quick access later? (Y/N)");
			String ch = lc.nextLine();
			if (ch.contains("y") || ch.contains("Y")) { favorites.add(ip + " " + port);  pw.println(ip + " " + port); pw.close(); System.out.println("Server saved.");}	
		}
	}
	catch (Exception e)
	{
		System.err.println("addFavorite encountered an exception: " + e);
		e.printStackTrace();
	}
}
 
开发者ID:DrDab,项目名称:mochaMUD,代码行数:20,代码来源:Runner.java

示例14: generateTestDataAndQueries

import java.io.PrintWriter; //导入依赖的package包/类
@BeforeClass
public static void generateTestDataAndQueries() throws Exception {
  // Table consists of two columns "emp_id", "emp_name" and "dept_id"
  empTableLocation = testTempFolder.newFolder().getAbsolutePath();

  // Write 100 records for each new file
  final int empNumRecsPerFile = 100;
  for(int fileIndex=0; fileIndex<NUM_EMPLOYEES/empNumRecsPerFile; fileIndex++) {
    File file = new File(empTableLocation + File.separator + fileIndex + ".json");
    PrintWriter printWriter = new PrintWriter(file);
    for (int recordIndex = fileIndex*empNumRecsPerFile; recordIndex < (fileIndex+1)*empNumRecsPerFile; recordIndex++) {
      String record = String.format("{ \"emp_id\" : %d, \"emp_name\" : \"Employee %d\", \"dept_id\" : %d }",
          recordIndex, recordIndex, recordIndex % NUM_DEPTS);
      printWriter.println(record);
    }
    printWriter.close();
  }

  // Initialize test queries
  groupByQuery = String.format("SELECT dept_id, count(*) as numEmployees FROM dfs.`%s` GROUP BY dept_id", empTableLocation);
}
 
开发者ID:skhalifa,项目名称:QDrill,代码行数:22,代码来源:TestPartitionSender.java

示例15: popupQrImageUpdateSubmit

import java.io.PrintWriter; //导入依赖的package包/类
/**
 * 通用电脑模式,更改底部的二维码,提交保存
 */
@RequestMapping(value = "popupQrImageUpdateSubmit")
public void popupQrImageUpdateSubmit(Model model,HttpServletRequest request,HttpServletResponse response,
		@RequestParam("qrImageFile") MultipartFile multipartFile) throws IOException{
	JSONObject json = new JSONObject();
	Site site = getSite();
	
	if(!(multipartFile.getContentType().equals("image/pjpeg") || multipartFile.getContentType().equals("image/jpeg") || multipartFile.getContentType().equals("image/png") || multipartFile.getContentType().equals("image/gif"))){
		json.put("result", "0");
		json.put("info", "请传入jpg、png、gif格式的二维码图");
	}else{
		//格式转换
		BufferedImage bufferedImage = ImageUtil.inputStreamToBufferedImage(multipartFile.getInputStream());
        BufferedImage tag = ImageUtil.formatConversion(bufferedImage);
        BufferedImage tag1 = ImageUtil.proportionZoom(tag, 400);
		
		//上传
        AttachmentFile.put("site/"+site.getId()+"/images/qr.jpg", ImageUtil.bufferedImageToInputStream(tag1, "jpg"));
		
		AliyunLog.addActionLog(getSiteId(), "通用电脑模式,更改底部的二维码,提交保存");
		
		json.put("result", "1");
	}
	
	response.setCharacterEncoding("UTF-8");  
    response.setContentType("application/json; charset=utf-8");  
    PrintWriter out = null;  
    try {  
        out = response.getWriter();  
        out.append(json.toString());
    } catch (IOException e) {  
        e.printStackTrace();  
    } finally {  
        if (out != null) {  
            out.close();  
        }  
    }  
}
 
开发者ID:xnx3,项目名称:wangmarket,代码行数:41,代码来源:SiteController.java


注:本文中的java.io.PrintWriter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。