Java 基础及常用写法

目录

 

1、Java 文件操作:

2、List去重:


 

 

1、Java 文件操作:

package busy.filestream;

import java.io.*;

public class Filestream {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File fs = new File("E:\\1java-temp\\test.txt");
		System.out.println("文件路径:" + fs.getPath());//文件路径
		System.out.println("文件大小:" + fs.length());//文件大小(字节)
		
		File fs1 = new File("E:\\1java-temp\\test2.txt");//创建文件
		if (!fs1.exists()) {
			try {
				fs1.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			System.out.println("文件存在,无法创建!");
		}
		
		File fs2 = new File("E:/1java-temp/newFile");//创建文件夹
		if (fs2.isDirectory()) {
			System.out.println("文件夹存在"); 
		}else {
			fs2.mkdir();
		}
		
		File fs3 = new File("E:\\");
		if( fs3.isDirectory()) {
			File lists[] = fs3.listFiles();
			for(int i = 0; i < lists.length; i ++) {
				System.out.println("文件名:"+lists[i].getName());
			}
		}
		
		File fs4 = new File("E:\\1java-temp\\test.txt");//读文件(这是字节流,还有字符流和字符串流)
		FileInputStream fsm = null;                 //FileReader(字符流),BufferReader(字符串流)
		try {
			fsm = new FileInputStream(fs4);
			byte []bytes = new byte[1024];
			int n = 0;//实际读取到的字节数
			while((n = fsm.read(bytes)) != -1) {
				String str = new String(bytes, 0, n);
				System.out.println(str);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fsm.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		File fs5 = new File("E:\\1java-temp\\test3.txt");//写文件
		FileOutputStream fsom = null;
		try {
			fsom = new FileOutputStream(fs5);
			String str = "一二三四五";
			fsom.write(str.getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fsom.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		File fs6 = new File("E:\\1java-temp\\img.jpg");//图片拷贝
		File fs7 = new File("E:\\1java-temp\\img1.jpg");
		FileInputStream fsm1 = null;
		FileOutputStream fsom1 = null;
		try {
			fsm1 = new FileInputStream(fs6);
			fsom1 = new FileOutputStream(fs7);
			byte buf[] = new byte[1024];
			int n = 0;
			while( (n = fsm1.read(buf)) != -1) {
				fsom1.write(buf);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				fsm1.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				fsom1.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}

}

2、List去重:

public static List removeDuplicate(List list) {   
    HashSet h = new HashSet(list);   
    list.clear();   
    list.addAll(h);   
    return list;   
}   

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Java)