java与python之编程之对比:一个简单的代码模板生成程序_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > java与python之编程之对比:一个简单的代码模板生成程序

java与python之编程之对比:一个简单的代码模板生成程序

 2011/10/11 8:12:18  banxi1988  http://banxi1988.iteye.com  我要评论(0)
  • 摘要:python部分的代码几乎是来息此文章:http://blog.sina.com.cn/s/blog_4419b53f0100abzb.html我小部分改进之后代码如下:#-*-coding:utf-8-*-#file:makeBasic.py#importosimportsysimportstringimportdatetime#python简单的脚本模板defmain():ifos.path.isfile(sys.argv[1]):print'%salreadyexist!'%sys
  • 标签:程序 模板 Java 一个 代码 Python 编程
python部分的代码几乎是来息此文章:
http://blog.sina.com.cn/s/blog_4419b53f0100abzb.html
我小部分改进之后代码如下:
#-*- coding:utf-8 -*-
# file :makeBasic.py
#
import os
import sys
import string
import datetime
# python 简单的脚本模板 
def main():
	if os.path.isfile(sys.argv[1]):
		print '%s already exist!' % sys.argv[1]
		sys.exit()
	basic_template = open(sys.argv[1],'w') # create a file in write mode
	today = datetime.date.today() # transform now to 'yyyy-mm-dd' s format
	date = today.strftime('%Y')+'-'+today.strftime('%m')+'-'+today.strftime('%d')
	filetypes = string.split(sys.argv[1],'.') # 判断文件类型
	length = len(filetypes)
	filetype = filetypes[length -1]
	print 'file type is :'+filetype
	if filetype == 'py':
		print 'use python mode'
		basic_template.writelines('#-*- coding:utf-8 -*-')
		basic_template.write('\n')
		basic_template.writelines('# file :'+sys.argv[1])
		basic_template.write('\n')
		basic_template.write('# date :'+date)
		basic_template.write('\n')
		 basic_template.write('##----------------------------------------------------')
		basic_template.write('\n')
		print 'template create successfully' 
	else:
		print 'not support other file time currently'
	basic_template.close() # 关闭文件
if __name__ == '__main__':
	main()
		


使用方法如下:
引用
banxi1988@banxi:~/work/python$ python makeBasic.py  fileRead.py
file type is :py
use python mode
template create successfully
banxi1988@banxi:~/work/python$


而用java来写呢!我自己写了如下一个:
我自己对于Java比较熟悉点,所以用Java写得自认为还是不错的.
从结构等方面来看都是容错性啊等等:
package me.banxi.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class MakeCode{
	public static void usage(){
		StringBuilder builder = new StringBuilder(1024);
		builder.append(" Usage:\n");
		builder.append(" unix-like: $ java MakeCode yourSourceFileName \n");
		builder.append(" example: $ java MakeCode HelloWorld.java");
		builder.append(" -------------------the end ------------------------------");
		System.out.println(builder.toString());
	}//:usage
	public static void notSupport(String fileName){
		String []strs = fileName.split(".");
		if(strs.length < 1) {
			System.out.println("you have not give a file .suffix! file type of "+fileName+"are not support now!");
		}else {
			System.out.println("file type of "+strs[strs.length-1]+"are not support now!");
		}

	}//:notSupport

	public  static boolean cancelCreate( String name ){
		System.out.println("file with name  of "+name+"is already exists!\n");
		System.out.println("do you want to build a new file?(y/n)");
		Scanner scanner  = new Scanner(System.in);
		String yesOrNo = scanner.next();
		if(yesOrNo.equalsIgnoreCase("y")) {
			return false;
		}
		return true;
		
	}//:isContinue
	
	private static void createTemplate(File file) {
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(file);
			StringBuilder builder = new StringBuilder(256);
			builder.append("import java.io.*;\n");
			builder.append("import java.util.*;\n");
			builder.append("/**\n");
			builder.append(" * @author yourName \n");
			builder.append(" * @date "+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
			builder.append("\n */\n");
			builder.append("public class "+file.getName());
			builder.append("{\n");
			builder.append("\n");
			builder.append("}\n");
			writer.write(builder.toString());
			writer.flush();
		} catch (FileNotFoundException e) {
			System.out.println("no such file:"+file.getAbsolutePath());
			e.printStackTrace();
		}finally {
			if(writer != null) {
				writer.close();
			}
		}
		
	}// :createTemplate


	public static void main(String ... args){
		if(args.length < 1){
			usage();
			System.exit(1);
		}//
		String fileName = args[args.length -1];
		if(fileName.endsWith(".java")){
			File file = new File(fileName);
			if(file.exists()){
				if(cancelCreate(file.getName())){
					System.exit(1);
				}
			}
			createTemplate(file);
			System.out.println("create java source template successfully!");
			System.out.println("file's full name was:"+file.getAbsolutePath());
		}else{
			notSupport(fileName);
			System.exit(1);
		}	

	}//

}//:end MakeCode
/**
 *   运行结果:
file with name  of MyFileReader.javais already exists!

do you want to build a new file?(y/n)
y
create java source template successfully!
file's full name was:/home/banxi1988/work/tomcat7/JavaIo/MyFileReader.java

生成模板内容:
import java.io.*;
import java.util.*;
**
 * @author yourName 
 * @date 2011-10-10 23:17:40
 *
public class MyFileReader.java{

}
 */




python版的我修改之后如下:
主要修改了,如果没有传递参数,提示用法.
时期精确到时分秒.
如果已经有文件了提示是否创建新的:
#-*- coding:utf-8 -*-
# file :makeBasic.py
#
import os
import sys
import string
from datetime import datetime
# python 简单的脚本模板 
def usage():
	usages = """
	 Usage:
	 unix-like usage:$ python makeBasic myfile.py
	 example :       $ python makeBasic helloworld.py
	"""
	print usages

def main():
	if len(sys.argv) < 2:
		usage()
		sys.exit()
		
	if os.path.isfile(sys.argv[1]):
		print '%s already exist!' % sys.argv[1]
		yesOrNo = raw_input ('do you still want to create a new file?(y/n)')
		if(yesOrNo.strip().lower() == 'n'):
			sys.exit()
	basic_template = open(sys.argv[1],'w') # create a file in write mode
	date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
	filetypes = string.split(sys.argv[1],'.') # 判断将创建的文件是什么类型然后分别处理
	length = len(filetypes)
	filetype = filetypes[length -1]
	print 'file type is :'+filetype
	if filetype == 'py':
		print 'use python mode'
		basic_template.writelines('#-*- coding:utf-8 -*-')
		basic_template.write('\n')
		basic_template.writelines('# file :'+sys.argv[1])
		basic_template.write('\n')
		basic_template.write('# date :'+date)
		basic_template.write('\n')
		basic_template.write('##----------------------------------------------------')
		basic_template.write('\n')
		print 'template create successfully' 
	else:
		print 'not support other file time currently'
	basic_template.close() # 关闭文件
if __name__ == '__main__':
	main()
		
上一篇: 关于ROR与PLAY 下一篇: java死锁
发表评论
用户名: 匿名