初学java的时候,我们不会写代码,其实这时候不妨趁有空的时候多背一些java代码,这样在进行java项目的时候,说不定还能用得了呢!那java初学者必背代码有哪些?下面来我们就来给大家讲解一下。
1. 字符串有整型的相互转换
String a = String.valueOf(2); //integer to numeric string int i = Integer.parseInt(a); //numeric string to an int
2. 向文件末尾添加内容
BufferedWriter out = null; try { 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("yyyy-MM-dd"); Date date = format.parse(myString);
5、类的属性和方法
public class Liwl { public String name = "liwanliang"; public Integer age = 30; public static void main(String[] args) { Liwl liwl01 = new Liwl(); //liwl01.name = "hello,world" System.out.println(liwl01.age) } } //通过liwl01.name = "hello,world"的语句,无法保证类的安全性,不太满足类的封装
6、列出文件和目录
File dir = new File("directoryName"); String children = dir.list; if (children == ) { // Either dir does not exist or is not a directory } else { for (int i = 0; i < children.length; 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);
多背java代码其实是积累java知识的一种方式,很多java开发语句我们不会写的时候,就可以将代码背下来,然后灵活应用!最后大家如果想要了解更多初识java知识,敬请关注奇Q工具网。
推荐阅读: