Java基础(五)(IO流,线程)

来源:互联网 发布:前线seo 编辑:程序博客网 时间:2024/06/02 04:02

IO流

java.io.File

1)创建File对象: new File(文件或目录路径字符串);  new File(父目录 , 文件或目录名);

2)文件目录属性:

      canRead(); canWrite(); canExecute(); exists(); getName(); getPath(); getParent(); getParentFile();

      isDirectory(); isFile(); isHidden(); lastModify(); length() 文件的字节量; 

      creatNewFile(); 创建文件,文件所在目录如果不存在,会出现异常

      createTempFIle(前缀 , 后缀); 在系统临时目录中创建临时文件

      delete();  删除文件或目录,对目录来说,只能删除空目录

      mkdir(); 创建目录,返回boolean表示是否创建成功

      mkdirs(); 创建多层目录,返回boolean 表示是否创建成功

      renameTo( File ); 重命名,返回 boolean 表示是否成功

3)目录列表方法:

      list(); 返回文件名称数组String[ ]

      listFiles(); 返回文件对象数组 File[ ]

      使用过滤器对文件列表进行过滤

     list(FilenameFilter); listFiles(FilenameFilter); listFiles(FileFilter);

      java.io.RandomAccessFile

文件读写工具,一般用于读写具有固定直接格式的文件,把文件看成是一个大型的字节数组。

new RandomAccessFile( File/FilePath , mode);  mode: "r"  "rw"  "rws"  "rwd"

方法:

      length(); 获得文件字节量

      seek(索引位置);

      getFilePointer(); 获得当前指针位置

      read(); 读取一个字节,前面补3个0字节,作int类型返回

      read(byte[ ]); 每次读取多个字节,放入指定数组,并返回这次读取的字节数量

      read(byte[ ] , 起始位置 , 最多读取个数);

      readInt(); 读取4个字节,作整数类型返回

      readDouble();

      readUTF(); 先读前两个字节,确定字节量,然后按字节量读取字符串

      write(int);将整数前三个字节不要,写出最后一个字节;

      writeInt(); 将int的四个字节写出

      writeDouble();

      writeUTF(); 先写两个字节表示字符串的字节量,再将表示字符串的字节写出

bmp图形:前54个字节,是bmp格式头。第19 - 22字节表示宽度,第23 - 26字节表示高度

java.io.InputStream

java.io.OutputStream

   FileOutputStream

   BufferedOutputStram;提供内存缓冲区,提高读写效率。默认缓冲区8k,可通过构造方法指定大小

   DataOutputStream;以字节方式读写数据,用于读写有固定格式的文件,方法与RandomAccess相同

   ByteArrayOutputStream

   PrintStream;将任何数据作为字符串输出


线程:

两种方式:继承Tread类,实现Rannable接口

方法:Thread.currentThread(); 获得正在执行此行代码的线程,获得当前线程

Thread.yield(); 放弃执行,让给其它线程执行

   Thread.sleep(毫秒值); 当前线程在此处暂停指定的时长

   getPriority(); setPriority(); 设置线程优先级[1 , 10],默认5,不要设置过高或过低的优先级

   interrupt(); 打断一个线程对象的休息

   isDaemon(); setDaemon(true); 将线程设置为Daemon线程:后台线程

   join(); 将另一线程加入到当前线程中,等待另一线程结束后,当前线程再继续,一般用于等待另一线程的     运算结果

   isAlive(); 判断是否是活动线程,start后,dead前

线程结束:不能用stop()方法,应该自己用逻辑控制线程结束,控制run方法结束,return ,throw

synchronized:

      同步关键字控制同步锁;一个线程执行同步快内的代码时,必须获得同步锁才能执行

synchronized代码块:线程安全,多个线程访问同一个数据时不会发生访问冲突,不会发生脏读。

wait(); 当前线程在调用的对象上等待,直到收到通知后继续执行;

wait(毫秒);

notify(); 通知一个等待的线程;

notifyAll(); 通知所有等待的线程

使用等待,通知,必须踩同步块内,wait和sleep区别:wait释放锁,sleep不释放锁

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.Reader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.os.Environment;public class FileUtil {private String SDPATH;String PACKAGE_NAME = "com.kuukaa.kxeg";public String DATABASE_PATH = "/data/data/" + PACKAGE_NAME;public String getSDPATH() {return SDPATH;}public FileUtil() {SDPATH = Environment.getExternalStorageDirectory() + "/";////////System.out.println(SDPATH);}public File[] getPathFiles(String path) {File f = new File(getSDPATH() + path);return f.listFiles();}public File createSDFile(String filename) throws IOException {File f = new File(getSDPATH() + filename);f.createNewFile();return f;}public boolean deleteSDFile(String filename) throws IOException {File f = new File(getSDPATH() + filename);return f.delete();}public File createSDDir(String dir) throws IOException {File d = new File(getSDPATH() + dir);if (!d.isDirectory())d.mkdir();return d;}public void createSDDirs(String dir) throws IOException {String[] dirs = dir.split("/");String temp = "";for (int i = 0; i < dirs.length; i++) {if (dirs[i] != null && dirs[i].length() > 0) {temp += "/" + dirs[i];createSDDir(temp);}}}public boolean isFileExist(String filename) {File f = new File(getSDPATH() + filename);return f.exists();}public boolean isFileExistPath(String filename) {File f = new File(filename);return f.exists();}//public File write2SDFromInput(String path, String filename, String input) throws IOException {//File file = null;//OutputStream out = null;////try {////createSDDirs(path);//file = createSDFile(path + "/" + filename);////out = new FileOutputStream(file);////OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");//BufferedWriter writer = new BufferedWriter(write);////PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(filePathAndName)));////PrintWriter writer = new PrintWriter(new FileWriter(filePathAndName));////writer.write(input);//writer.close();////} catch (FileNotFoundException e) {//throw e;//} catch (IOException e) {//throw e;//} /*finally{//try {//out.close();//} catch (IOException e) {//throw e;//}//}*/////return file;//}/** * 将一个InputStream里面的数据写入到SD卡中 */public File writeToSDFromInput(String path, String fileName, InputStream input) {File file = null;OutputStream output = null;try {createSDDir(path);file = createSDFile(path + fileName);output = new FileOutputStream(file);byte buffer[] = new byte[1024];int len = 0;//如果下载成功就开往SD卡里些数据while ((len = input.read(buffer)) != -1) {output.write(buffer, 0, len);}output.flush();} catch (Exception e) {e.printStackTrace();} finally {try {input.close();output.close();} catch (Exception e) {e.printStackTrace();}}return file;}public String reader2Str(String path, String filename) throws FileNotFoundException, IOException, UnsupportedEncodingException {StringBuffer sb = new StringBuffer();InputStreamReader isr;try {isr = new InputStreamReader(new FileInputStream(new File(getSDPATH() + path + "/" + filename)), "GBK");BufferedReader br = new BufferedReader(isr);String str = "";while ((str = br.readLine()) != null) {sb.append(str);}} catch (UnsupportedEncodingException e) {throw e;} catch (FileNotFoundException e) {throw e;} catch (IOException e) {throw e;}return sb.toString();}public List reader2List(String path, String filename) throws FileNotFoundException, IOException, UnsupportedEncodingException {List<String> sb = new ArrayList();if (sb != null && sb.size() > 0)return sb;InputStreamReader isr;try {isr = new InputStreamReader(new FileInputStream(new File(getSDPATH() + path + "/" + filename)), "GBK");BufferedReader br = new BufferedReader(isr);String str = "";while ((str = br.readLine()) != null) {sb.add(str.trim());}} catch (UnsupportedEncodingException e) {throw e;} catch (FileNotFoundException e) {throw e;} catch (IOException e) {throw e;}return sb;}public File createDATADir(String dir) throws IOException {File d = new File(DATABASE_PATH + "/" + dir);if (!d.exists())d.mkdir();return d;}public void savetext(Context con) {try {FileOutputStream outStream = con.openFileOutput(DATABASE_PATH + "/zip/a.txt", Context.MODE_WORLD_READABLE);outStream.write("asdf".getBytes());outStream.close();} catch (FileNotFoundException e) {return;} catch (IOException e) {return;}}public void loadtext(Context con) {try {FileInputStream inStream = con.openFileInput(DATABASE_PATH + "/zip/a.txt");ByteArrayOutputStream stream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length = -1;while ((length = inStream.read(buffer)) != -1) {stream.write(buffer, 0, length);}stream.close();inStream.close();////System.out.println(stream);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {return;}}}

public static String readFromSDcard(String fileName) {String fileContent = "";try {File f = new File("/mnt/sdcard/" + fileName);if (f.isFile() && f.exists()) {InputStreamReader read = new InputStreamReader(new FileInputStream(f), "gbk");BufferedReader reader = new BufferedReader(read);String line;while ((line = reader.readLine()) != null) {fileContent += line;}read.close();}} catch (Exception e) {e.printStackTrace();}return fileContent;}/* 写入到文件 */public static void writeFile(String fileName, String fileContent) {try {File f = new File(fileName);if (!f.exists()) {f.createNewFile();}OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "gbk");BufferedWriter writer = new BufferedWriter(write);writer.write(fileContent);writer.close();} catch (Exception e) {e.printStackTrace();}}




     

原创粉丝点击