Java新手要敲好Java敲代码用什么笔记本有什么技巧吗

Java程序员:世上最远的距离,莫过于我在敲代码而你不敲!Java程序员:世上最远的距离,莫过于我在敲代码而你不敲!青枳科技百家号1,哎呀,加班啊......2,这两个程序员回答就比较中肯了,一看就是大佬3,“拉仇恨型的”程序员,4,“无所谓”咯其实.......Java程序员学习交流群,既有技术大佬,又有老司机开车,各位对Java感兴趣的可以来交流学习一下,快乐与技术一起进步。本文仅代表作者观点,不代表百度立场。系作者授权百家号发表,未经许可不得转载。青枳科技百家号最近更新:简介:科普科技知识用心来听作者最新文章相关文章我学过C++现在在自学JAVA谁能给我点建议!我现在学JAVA都只能敲几个简单程序!谁能给点指导?_百度知道
我学过C++现在在自学JAVA谁能给我点建议!我现在学JAVA都只能敲几个简单程序!谁能给点指导?
我有更好的答案
张孝祥老师的《Java就业培训教程》图书和配套视频光盘感觉不错,比较实用,我的qq:,有什么问题可以问我
采纳率:46%
com优酷网:
两者都很相像的 看看书 很容易理解 可以看看java核心技术2 这个书
为您推荐:
其他类似问题
您可能关注的内容
java的相关知识
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。博客分类:
转贴来源:
下面是20个非常有用的Java程序片段,希望能对你有用。1. 字符串有整型的相互转换
String a = String.valueOf(2);
//integer to numeric string
int i = Integer.parseInt(a); //numeric string to an int
2. 向文件末尾添加内容
BufferedWriter out =
out = new BufferedWriter(new FileWriter(”filename”, true));
out.write(”aString”);
} catch (IOException e) {
// error processing code
} finally {
if (out != null) {
out.close();
3. 得到当前方法的名字
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
4. 转字符串到日期
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );
Date date = format.parse( myString );
5. 使用JDBC链接Oracle
public class OracleJdbcTest
String driverClass = "oracle.jdbc.driver.OracleDriver";
public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException
Properties props = new Properties();
props.load(fs);
String url = props.getProperty("db.url");
String userName = props.getProperty("db.user");
String password = props.getProperty("db.password");
Class.forName(driverClass);
con=DriverManager.getConnection(url, userName, password);
public void fetch() throws SQLException, IOException
PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");
ResultSet rs = ps.executeQuery();
while (rs.next())
// do the thing you do
rs.close();
ps.close();
public static void main(String[] args)
OracleJdbcTest test = new OracleJdbcTest();
test.init();
test.fetch();
6. 把 Java util.Date 转成 sql.Date
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
7. 使用NIO进行快速的文件拷贝
public static void fileCopy( File in, File out )
throws IOException
FileChannel inChannel = new FileInputStream( in ).getChannel();
FileChannel outChannel = new FileOutputStream( out ).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
// original -- apparently has trouble copying large files on Windows
// magic number for Windows, 64Mb - 32Kb)
int maxCount = (64 * 1024 * 1024) - (32 * 1024);
long size = inChannel.size();
long position = 0;
while ( position & size )
position += inChannel.transferTo( position, maxCount, outChannel );
if ( inChannel != null )
inChannel.close();
if ( outChannel != null )
outChannel.close();
8. 创建图片的缩略图
private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
throws InterruptedException, FileNotFoundException, IOException
// load image from filename
Image image = Toolkit.getDefaultToolkit().getImage(filename);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
// use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());
// determine thumbnail size from WIDTH and HEIGHT
double thumbRatio = (double)thumbWidth / (double)thumbH
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double)imageWidth / (double)imageH
if (thumbRatio & imageRatio) {
thumbHeight = (int)(thumbWidth / imageRatio);
thumbWidth = (int)(thumbHeight * imageRatio);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
// save thumbnail image to outFilename
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
9. 创建 JSON 格式的数据
请先阅读这篇文章 了解一些细节,
并下面这个JAR 文件:json-rpc-1.0.jar (75 kb)
import org.json.JSONO
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
String output = json.toString();
10. 使用iText JAR生成PDF
阅读这篇文章 了解更多细节
import java.io.F
import java.io.FileOutputS
import java.io.OutputS
import java.util.D
import com.lowagie.text.D
import com.lowagie.text.P
import com.lowagie.text.pdf.PdfW
public class GeneratePDF {
public static void main(String[] args) {
OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
document.add(new Paragraph("Hello Kiran"));
document.add(new Paragraph(new Date().toString()));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
11. HTTP 代理设置
阅读这篇 文章 了解更多细节。
System.getProperties().put("http.proxyHost", "someProxyURL");
System.getProperties().put("http.proxyPort", "someProxyPort");
System.getProperties().put("http.proxyUser", "someUserName");
System.getProperties().put("http.proxyPassword", "somePassword");
12. 单实例Singleton 示例
请先阅读这篇文章 了解更多信息
public class SimpleSingleton {
private static SimpleSingleton singleInstance =
new SimpleSingleton();
//Marking default constructor private
//to avoid direct instantiation.
private SimpleSingleton() {
//Get instance for class SimpleSingleton
public static SimpleSingleton getInstance() {
return singleI
另一种实现
public enum SimpleSingleton {
public void doSomething() {
//Call the method from Singleton:
SimpleSingleton.INSTANCE.doSomething();
13. 抓屏程序
阅读这篇文章 获得更多信息。
import java.awt.D
import java.awt.R
import java.awt.R
import java.awt.T
import java.awt.image.BufferedI
import javax.imageio.ImageIO;
import java.io.F
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
14. 列出文件和目录
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
for (int i=0; i & children. i++) {
// Get filename of file or directory
String filename = children[i];
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
files = dir.listFiles(fileFilter);
15. 创建ZIP和JAR文件
import java.util.zip.*;
import java.io.*;
public class ZipIt {
public static void main(String args[]) throws IOException {
if (args.length & 2) {
System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");
System.exit(-1);
File zipFile = new File(args[0]);
if (zipFile.exists()) {
System.err.println("Zip file already exists, please try another");
System.exit(-2);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
int bytesR
byte[] buffer = new byte[1024];
CRC32 crc = new CRC32();
for (int i=1, n=args. i & i++) {
String name = args[i];
File file = new File(name);
if (!file.exists()) {
System.err.println("Skipping: " + name);
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
crc.reset();
while ((bytesRead = bis.read(buffer)) != -1) {
crc.update(buffer, 0, bytesRead);
bis.close();
// Reset to beginning of input stream
bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setCompressedSize(file.length());
entry.setSize(file.length());
entry.setCrc(crc.getValue());
zos.putNextEntry(entry);
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
bis.close();
zos.close();
16. 解析/读取XML 文件
&?xml version="1.0"?&
&students&
&name&John&/name&
&grade&B&/grade&
&age&12&/age&
&/student&
&name&Mary&/name&
&grade&A&/grade&
&age&11&/age&
&/student&
&name&Simon&/name&
&grade&A&/grade&
&age&18&/age&
&/student&
&/students&
package net.viralpatel.java.
import java.io.F
import javax.xml.parsers.DocumentB
import javax.xml.parsers.DocumentBuilderF
import org.w3c.dom.D
import org.w3c.dom.E
import org.w3c.dom.N
import org.w3c.dom.NodeL
public class XMLParser {
public void getAllUserNames(String fileName) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File file = new File(fileName);
if (file.exists()) {
Document doc = db.parse(file);
Element docEle = doc.getDocumentElement();
// Print root element of the document
System.out.println("Root element of the document: "
+ docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName("student");
// Print total student elements in document
System.out
.println("Total students: " + studentList.getLength());
if (studentList != null && studentList.getLength() & 0) {
for (int i = 0; i & studentList.getLength(); i++) {
Node node = studentList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("=====================");
Element e = (Element)
NodeList nodeList = e.getElementsByTagName("name");
System.out.println("Name: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("grade");
System.out.println("Grade: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
nodeList = e.getElementsByTagName("age");
System.out.println("Age: "
+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue());
System.exit(1);
} catch (Exception e) {
System.out.println(e);
public static void main(String[] args) {
XMLParser parser = new XMLParser();
parser.getAllUserNames("c:\\test.xml");
17. 把 Array 转换成 Map
import java.util.M
import org.apache.commons.lang.ArrayU
public class Main {
public static void main(String[] args) {
String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
{ "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
Map countryCapitals = ArrayUtils.toMap(countries);
System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
System.out.println("Capital of France is " + countryCapitals.get("France"));
18. 发送邮件
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
boolean debug =
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i & recipients. i++)
addressTo[i] = new InternetAddress(recipients[i]);
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
19. 发送代数据的HTTP 请求
import java.io.BufferedR
import java.io.InputStreamR
import java.net.URL;
public class Main {
public static void main(String[] args)
URL my_url = new URL("http://coolshell.cn/");
BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
String strTemp = "";
while(null != (strTemp = br.readLine())){
System.out.println(strTemp);
} catch (Exception ex) {
ex.printStackTrace();
20. 改变数组的大小
查看源代码打印帮助
* Reallocates an array with a new size, and copies the contents
* of the old array to the new array.
* @param oldArray
the old array, to be reallocated.
* @param newSize
the new array size.
A new array with the same contents.
private static Object resizeArray (Object oldArray, int newSize) {
int oldSize = java.lang.reflect.Array.getLength(oldArray);
Class elementType = oldArray.getClass().getComponentType();
Object newArray = java.lang.reflect.Array.newInstance(
elementType,newSize);
int preserveLength = Math.min(oldSize,newSize);
if (preserveLength & 0)
System.arraycopy (oldArray,0,newArray,0,preserveLength);
return newA
// Test routine for resizeArray().
public static void main (String[] args) {
int[] a = {1,2,3};
a = (int[])resizeArray(a,5);
for (int i=0; i&a. i++)
System.out.println (a[i]);
浏览: 162451 次
来自: 山西
wgrmmtmr 写道let g:miniBufExplMap ...
let g:miniBufExplMapWindowsNavV ...
avi9111 写道还是同样问题,你这个代码ctrl+c和ct ...
还是同样问题,
你这个代码
ctrl+c和ctrl+v粘贴能处 ...
ILoveDOUZHOU 写道windows下为什么使用vim ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'积极主动敲代码,使用JUnit学习Java
早起看到在知乎的回答,很有感触。
从读大学算起,我敲过不下100本程序设计图书的代码,我的学习经验带来我的程序设计教学方法是:程序设计入门,最有效的方法要积极主动敲代码。这也就是为什么我要求同学们把教材上的代码动手敲一遍的原因。
引用一下徐宥的例子:
记得《The TeXbook》上有一个程序,Knuth让大家自己照着敲入计算机,然后还很幽默地说,实验证明,只有很少的人会按照他说的敲入这个程序,而这部分人,却是学TeX学得最好的人。看到这里我会心一笑,觉得自己的方法原来也不算笨。从此,一字不漏敲入一本书的程序成了我推荐别人学习语言的最好办法。
针对《Java程序设计》课程,我可以改写一下,实验证明:只有很少的同学会按照我说的敲入教材上的程序,而这部分人,却是学Java学得最好的人。我知道那些所谓“把书上代码都敲了,但还是搞不懂”的同学是怎么回事,所以我验收代码的第一个问题是“代码是自己敲的吗?”
好吧,我承认个别同学真的敲了代码还不明白怎么回事,问题出在敲代码没有积极主动上,为了让这部分同学掌握学习方法,我给出一个敲代码的例子。
下面有个StringBuffer的例子,代码如下:
1 public class StringBufferDemo{
public static void main(String [] args){
StringBuffer buffer = new StringBuffer();
buffer.append('S');
buffer.append(&tringBuffer&);
System.out.println(buffer.charAt(1));
System.out.println(buffer.capacity();
System.out.println(buffer.indexOf(&tring&));
System.out.println(&buffer = & + buffer.toString());
作为初学者的你们,在敲代码的时候肯定会遇到很多问题:大小写,丢字母,中英文字符,文件命名等,能让这个程序顺利编译就能学到不少知识。顺便说一下,上面的代码直接拷贝是不能够用javac StringBufferDemo.java直接编译成功的,你可以试一下。
程序编译通过后,如果直接用java StringBufferDemo运行一下程序,看一下运行结果,这样学不到太多。一种较好的做法是自己先理解代码,推导一下可能的结果,如果运行结果和自己想象的一样,基本就理解了代码,否则就有知识盲点,要深入学习了。
上面的代码,第3行构建了一个空StringBuffer的对象buffer,第4、5行调用两次append后,buffer的内容应该是“StringBuffer”, Java中的函数看一下名字就差不多猜出来它的功能了,我们猜一下后面的代码的结果:
第6行:charAt(1)应该是返回字符串中的第1个字符,很可能是‘S’或‘t’,考虑到程序设计中数组等编号都是从0开始,最有可能是‘t’
第7行:capacity大概是返回字符串的容量,字符串“StringBuffer”的长度是12,猜一下,12?
第8行:indexOf是子串匹配,与第6行问题差不多,可能是1,2,最可能是1
代码编译、运行的结果是:
buffer = StringBuffer
看来除了第7行,其他都猜对了。这时候是该看看StringBuffer的帮助文档了。不大好用,在Windows下的话,推荐大家,这个版本的API具个检索功能,用好了,很快可以掌握举一反三的自学能力,当然要有一点点的英语基础了。补全见下图:
比如我们想对几个数进行排序,你如果知道「排序」的英文单词是「sort」,那么你可以找到一堆可以解决你问题的方法来,是不是有了在搜索引擎中使用关键词进行搜索的感觉?如下图。
我们看看StringBuffer的capacity的帮助文档:
看不懂?去查一下不认识的单词的意思吧,然后把单词加入自己的记忆列表吧。计算机的英语都比较简单,英语不懂,翻译成汉语也还是不懂,因为缺少的是专业知识,而不仅仅是语言。有汉化版的,下面的能看懂吗?
好象没有什么帮助。我们需要通过修改代码来理解这个方法了。把上面代码中的第4、5、6、8行屏蔽掉,让buffer是个空串看看是什么结果,结果如下:
哦,明白了,capacity返回的不是字符串的长度,而是目前的最大容量。那要获得字符串的长度用哪个方法?查找一下StringBuffer的Method Summary,好象应该是length(),如下图:
我们增加一行代码调用一下length():
1 public class StringBufferDemo{
public static void main(String [] args){
StringBuffer buffer = new StringBuffer();
buffer.append('S');
buffer.append(&tringBuffer&);
System.out.println(buffer.charAt(1));
System.out.println(buffer.capacity();
System.out.println(buffer.indexOf(&tring&));
System.out.println(&buffer = & + buffer.toString());
System.out.println(buffer.length());
程序运行结果如下:
buffer = StringBuffer
这下明白了capacity()和length()的关系,前者是最大容量,默认是16,length返回当前长度。如果学过《数据结构》相关的课程并用到过extern void *realloc(void *mem_address, unsigned int newsize);就更容易理解了。如果字符串超过16个字符呢?我们修改代码如下:
1 public class StringBufferDemo{
public static void main(String [] args){
StringBuffer buffer = new StringBuffer();
buffer.append('S');
buffer.append(&tringBuffer&);
System.out.println(buffer.charAt(1));
System.out.println(buffer.capacity();
System.out.println(buffer.indexOf(&tring12345&));
System.out.println(&buffer = & + buffer.toString());
System.out.println(buffer.length());
程序运行结果如下:
buffer = StringBuffer
哦,超过16个字符会再分配18个字符的空间。那超过34个字符呢?你猜猜capacity()的返回值(52?54?56?还是其他值)并修改上面的代码验证一下。
其实学习Java中的任何一个新类时,首先要学习一下其构造方法,我们看一下StringBuffer的构造方法,如下图:
汉化版如下:
原来我们可以构造StringBuffer时指定其capacity的,如果不指定默认值是16,我们修改代码如下:
1 public class StringBufferDemo{
public static void main(String [] args){
StringBuffer buffer = new StringBuffer(20);
buffer.append('S');
buffer.append(&tringBuffer&);
System.out.println(buffer.charAt(1));
System.out.println(buffer.capacity();
System.out.println(buffer.indexOf(&tring12345&));
System.out.println(&buffer = & + buffer.toString());
System.out.println(buffer.length());
程序运行结果如下:
buffer = StringBuffer
这时对capacity的理解是不是更深入了?
当然,如果能想到StringBuilder和String有什么不同,到网上找一下类「《》」这类的文章看看就更积极主动了。
对于Java API中的类、方法,我们学习时写个测试类很利于我们理解类和方法的功能。我们在中学习了单元测试和,使用改写教材上的例子是积极主动敲代码的好途径。
比如下面这个代码,equals方法的代码要好好理解。equals实现了等价关系,满足:
自反性 (reflexive):对于任何一个非null的引用值x,x.equals(x)为true。
对称性 (symmetric):对于任何一个非null的引用值x和y,x.equals(y)为true时y.equals(x)为true。
传递性 (transitive):对于任何一个非null的引用值x、y和z,当x.equals(y)为true 且 y.equals(z)为true 则 x.equals(z)为true。
一致性 (consistent):对于任何一个非null的引用值x和y,只要equals的比较操作在对象中所用的信息没有被修改,多次调用x.equals(y)的结果依然一致。
另外还要满足:对于任何非null的引用值x,x.equals(null)必须返回false。
public class Score {
private int No;
public ScoreClass() {
//无参数的构造方法
No = 1000;
score = 0;
public ScoreClass(int n, int s) {
//有两个参数的构造方法
public void setInfo(int n, int s) {
//设置成绩
public int getNo() {
return No;
//获取学号
public int getScore() {
//获取成绩
public String toString() {
return No + &\t& +
public boolean equals(Object obj) {
if (this == obj) {
// 是否引用同一个对象
if (obj == null) {
// 是否为空
if (getClass() != obj.getClass()) {
// 是否属于同一个类型
ScoreClass other = (ScoreClass)
if (other.No == No && other.score == score) {
参考,在你熟悉的Java IDE中(、或)中利用写一些测试代码,要求能测到equals中的每一个return,动手试试吧!
当然,积极主动是一种学习态度,看看学姐在我另一门课如何积极主动学习的「」,我说多思考了吗?深度思考对一个人的成长太重要了。
进一步参考
欢迎关注“rocedu”微信公众号(手机上长按二维码)
做中教,做中学,实践中共同进步!
原文地址:
推荐网站:、、、、、
版权声明:自由转载-非商用-非衍生-保持署名|
阅读(...) 评论()}

我要回帖

更多关于 敲代码 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信