文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Java 在学习三十七【原创】  


Java 7 异常表达式:

package tryTest;


import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.InputStreamReader;


public class Test9 {


public static void main(String[] args) {

// TODO Auto-generated method stub

String tempstr = "";

try(FileInputStream input = new FileInputStream("/Users/houhuiyang/Web/Java/test.txt")) {

BufferedReader br = new BufferedReader(new InputStreamReader(input));

StringBuffer sb = new StringBuffer();

while((tempstr = br.readLine()) != null) {

sb.append(tempstr + "\n");

}

System.out.println(sb);

} catch(Exception e) {

e.printStackTrace();

}

}


}


Java IO的学习

java.io包:

编码问题

写入文件-》字符串的序列化;

读取文件-》字符串的反序列化;

文本文件中的内容都是以字节方式呈现的;


package ioJava;


import java.io.UnsupportedEncodingException;


public class Test1 {


public static void main(String[] args) {

// TODO Auto-generated method stub

try {

String a = "滴滴打车"; //UTF-8 3*4 = 12个字节

byte[] b;

b = a.getBytes("UTF-8");

for (byte c : b) {

System.out.print(Integer.toHexString(c & 0xFF) + ",");

}

System.out.println("\n####################");

String s = new String(b, "UTF-8");

System.out.println(s);

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


java.io.File 即可以表示目录也可以表示一个文件;

package ioJava;


import java.io.File;

import java.io.IOException;


public class Test2 {


public static void main(String[] args) {

File f = new File("/Users/houhuiyang/Web/Java/HHY-JAVA");

System.out.println(f.isDirectory());

System.out.println(f.isFile());

System.out.println(f.isFile());

if (f.exists()) {

f.delete();

} else {

f.mkdir(); // 有多级目录用mkdirs

}

System.out.println("##################");

try {

File f2 = new File("/Users/houhuiyang/Web/Java/", "20170623.txt");

f2.createNewFile();

System.out.println("##################");

System.out.println(f2.getAbsolutePath());

System.out.println(f2.getName());

} catch (IOException e) {

e.printStackTrace();

}


}


}

文件的过滤操作;

package ioJava;


import java.io.File;

import java.io.FilenameFilter;


public class Test3 {


public static void main(String[] args) {

File f = new File("/Users/houhuiyang/Web/Java");

listFile(f);

}

static class MyFilenameFilter implements FilenameFilter {


@Override

public boolean accept(File dir, String name) {

System.out.println(dir.getAbsolutePath() + "---" + name);

//return true;

return name.endsWith(".java");

}


}

public static void listFile(File file) {

// 文件名 String

// String[] filenames = file.list();

// for (String s : filenames) {

// System.out.println(s);

// }

// 全目录 Object

File[] filenames1 = file.listFiles(new MyFilenameFilter());

for (File s : filenames1) {

if (s.isDirectory()) {

listFile(s);

//System.out.println("####################");

} else {

System.out.println(s);

}

}

}


}