Java IO 一些基本操作

passport_daizi發表於2012-06-15

java讀取檔案:

1:一行一行讀取

package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Test {
	public static void main(String[] args) {
		String filename = "c:/test.xml";
		Test t = new Test();
		System.out.println(t.readFileToString(filename));
	}
	
	public String readFileToString(String filename){
		StringBuffer sb = new StringBuffer();
		File file = new File(filename);
		try {
			FileInputStream in = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(in,"utf-8");
			BufferedReader br = new BufferedReader(isr);
			String linetext = null;
			while((linetext = br.readLine()) != null){
				sb.append(linetext);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}
}




java常用基礎技術,本人整理了一些,分享,會不斷更新,並送大家一些積分

JAVA群中,經常有人問我這些問題,我總結了一下,並整理出來,想必很多人也會問到這些問題.我帖在這裡.
並且散發一些積分,送給群內一些朋友.

java
得到檔案路徑下的所有檔名
] /* * @param
宣告File物件,指定引數filePath */
File dir = new File(filePath); //
返回此抽象路徑下的檔案
File[] files = dir.listFiles();
if (files == null) return;
for (int i = 0; i < files.length; i++) { //
判斷此檔案是否是一個檔案
if (
files[i].isDirectory())
{ System.out.println(files[i].getName()); } }

--------------------------------
1.
建立檔案:
/**  
     *
上傳檔案  
     *   
     * @param file
上傳檔案實體  
     * @param filename
上傳檔案新命名  
     * @param dir  
上傳檔案目錄  
     * @return  
     */  
    public static boolean uploadFile(File file, String dir,String filename) {   
        boolean ret =false;   
        try {   
            if(file != null) {   
               java.io.File filePath = new java.io.File(dir);   
               if (!filePath.exists()) {   
                    filePath.mkdir();   
               }   
               String target = dir + filename;   
               FileOutputStream outputStream = new FileOutputStream(target);   
               FileInputStream fileIn = new FileInputStream(file);   
               byte[] buffer = new byte[1024];   
               int len;   
               while ((len = fileIn.read(buffer)) > 0) {   
                    outputStream.write(buffer,0, len);   
               }   
               fileIn.close();   
               outputStream.close();   
               ret = true;   
            }   
        } catch (Exception ex){   
            log.info("
上傳檔案無法處理,請確認上傳檔案!");   
        }   
        return ret;   
    }  
---------------------------------
刪除檔案:
/**  
     *
刪除檔案  
     *   
     * @param filePathAndName
刪除檔案完整路徑:d:/filedir/filename  
     * @return  
     */  
    public static boolean delFile(String filePathAndName){   
        boolean ret =false;   
        try {   
            newFile(filePathAndName.toString()).delete();   
            ret =true;   
  
        } catch (Exception e){   
            System.out.println("
刪除檔案操作出錯");   
            e.printStackTrace();   
        }   
        return ret;   
    }  
----------------------------------------
刪除目錄下全部檔案:
/**  
     *
刪除目錄下的檔案  
     *   
     * @param dir
檔案目錄d:/filedir/  
     * @return  
     */  
    public static boolean delFiles(String dir){   
        boolean ret =false;   
        try {   
            FilefilePath = new File(dir);//
查詢路徑   
            String[]files = filePath.list();//
存放所有查詢結果   
            int i =0;   
            for (i= 0; i < files.length; i++) {   
               new java.io.File(dir + "/" + files[i]).delete();   
            }   
            ret =true;   
        } catch (Exception e){   
            e.printStackTrace();   
        }   
        return ret;   
    }  
--------------------------------------------
.
判斷檔案是否存在

/**  
     *
判斷檔案是否存在  
     *   
     * @param filename  
     * @return  
     */  
    public static boolean isExist(String filename){   
        boolean ret =false;   
        try {   
            Filefile = new File(filename.toString());   
            if(file.exists()) {   
               ret = true;   
            }   
        } catch (Exception e){   
            e.printStackTrace();   
        }   
        return ret;   
    }  
-------------------------------------------------
根據制定路徑,可以獲取當前正在操作的檔案的大小,容量為byte.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class FileByte {
private String filePath = "D:\\m07012600030000001_z.wav";
private void getFileByte(){
          File f = newFile(filePath)   ;   
          try{   
            FileInputStreamfis = new FileInputStream(f) ;   
            try   {   
            System.out.println(fis.available())   ;   
            }catch(IOExceptione1){   
            e1.printStackTrace();   
            }   
            }catch(FileNotFoundExceptione2){   
            e2.printStackTrace();   
            }   
      }


public static void main(String[] args)
{
    FileByte fb = new FileByte();
    fb.getFileByte();


}

}
-------------------------------------------------------
如何用java獲取網路檔案的大小(多執行緒
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class saveToFile {
public void saveToFile(String destUrl, String fileName) throws IOException
{
     FileOutputStream fos = null;
     BufferedInputStream bis = null;
     HttpURLConnection httpUrl = null;
     URL url = null;
     byte[] buf = new byte[2];
     int size = 0;
     int s=0;
     //
建立連結
    url = new URL(destUrl);
     httpUrl = (HttpURLConnection)url.openConnection();
     //
連線指定的資源
     httpUrl.connect();
     //
獲取網路輸入流
     bis = newBufferedInputStream(httpUrl.getInputStream());
     //
建立檔案
     fos = new FileOutputStream(fileName);
     
System.out.println("
正在獲取連結[" + destUrl+ "]的內容...\n將其儲存為檔案[" + fileName + "]");
     //
儲存檔案
     while ( (size = bis.read(buf)) != -1)
     {
     fos.write(buf, 0, size);
     //++s;
     System.out.println(size);
     //System.out.println(s/1024+"M");
     }
      
     fos.close();
     bis.close();
     httpUrl.disconnect();
   }

  
//
多執行緒檔案下載程式:
public class DownloadNetTest {
    private File fileOut;
    private java.net.URL url;
    private long fileLength=0;
    //
初始化執行緒數
    private int ThreadNum=5;
    public DownloadNetTest(){
    try{
       System.out.println("
正在連結URL");
       url=newURL("http://211.64.201.201/uploadfile/nyz.mp3");
       HttpURLConnectionurlcon=(HttpURLConnection)url.openConnection();
       //
根據響應獲取檔案大小
       fileLength=urlcon.getContentLength();
       if(urlcon.getResponseCode()>=400){
       System.out.println("
伺服器響應錯誤");
       System.exit(-1);
       }
       if(fileLength<=0)
       System.out.println("
無法獲知檔案大小");
       //
列印資訊
       printMIME(urlcon);
       System.out.println("
檔案大小為"+fileLength/1024+"K");
       //
獲取檔名
       String trueurl=urlcon.getURL().toString();
       Stringfilename=trueurl.substring(trueurl.lastIndexOf('/')+1);
       fileOut=newFile("D://",filename);
    }
    catch(MalformedURLException e){
       System.err.println(e);
    }
    catch(IOException e){
       System.err.println(e);
    }
    init();
}
    private void init(){
       DownloadNetThread [] down=newDownloadNetThread[ThreadNum];
    try {
       for(int i=0;i<ThreadNum;i++){
          RandomAccessFilerandOut=new RandomAccessFile(fileOut,"rw");
         randOut.setLength(fileLength);
          longblock=fileLength/ThreadNum+1;
          randOut.seek(block*i);
          down[i]=newDownloadNetThread(url,randOut,block,i+1);
          down[i].setPriority(7);
          down[i].start();
       }
    //
迴圈判斷是否下載完畢
    boolean flag=true;
    while (flag) {
       Thread.sleep(500);
       flag = false;
       for (int i = 0; i < ThreadNum; i++)
       if (!down[i].isFinished()) {
       flag = true;
       break;
       }
   }// end while
    System.out.println("
檔案下載完畢,儲存在"+fileOut.getPath());
    } catch (FileNotFoundException e) {
          System.err.println(e);
          e.printStackTrace();
    }
    catch(IOException e){
       System.err.println(e);
       e.printStackTrace();
    }
    catch (InterruptedException e) {
    System.err.println(e);
    }
}
private void printMIME(HttpURLConnection http){
    for(int i=0;;i++){
    String mine=http.getHeaderField(i);
    if(mine==null)
    return;
   System.out.println(http.getHeaderFieldKey(i)+":"+mine);
    }
}


//
執行緒類
public class DownloadNetThread extends Thread{
private InputStream randIn;
private RandomAccessFile randOut;
private URL url;
private long block;
private int threadId=-1;
private boolean done=false;
    public DownloadNetThread(URL url,RandomAccessFile out,longblock,int threadId){
    this.url=url;
    this.randOut=out;
    this.block=block;
    this.threadId=threadId;
}
  public void run(){
    try{
       HttpURLConnectionhttp=(HttpURLConnection)url.openConnection();
      http.setRequestProperty("Range","bytes="+block*(threadId-1)+"-");
       randIn=http.getInputStream();
    }
    catch(IOException e){
       System.err.println(e);
    }
    ////////////////////////
    byte [] buffer=new byte[1024];
    int offset=0;
    long localSize=0;
    System.out.println("
執行緒"+threadId+"開始下載");
    try {
       while ((offset = randIn.read(buffer)) !=-1&&localSize<=block) {
       randOut.write(buffer,0,offset);
       localSize+=offset;
       }
       randOut.close();
       randIn.close();
       done=true;
       System.out.println("
執行緒"+threadId+"完成下載");
       this.interrupt();
    }
    catch(Exception e){
       System.err.println(e);
    }
}
   public boolean isFinished(){
      return done;
   }
}


}
/*public static void main(String[] args) {
        DownloadNetTest app=new DownloadNetTest();
} */

}

----------------------------

pom.xml
裡面宣告javajar
dependency>   
         <groupId>com.sun</groupId>   
         <artifactId>tools</artifactId>   
          <version>1.6.0<ersion>   
         <scope>system</scope>   
          <systemPath>C:/ProgramFiles/Java k1.6.0_05 b/tools.jar</systemPath>   
   </dependency>

----------------------------------------------
獲取的路徑裡有空格變成20%以後,用什麼把這個還原
String path = "111120%";
path=path.replace
"20%","";

13795111413
----------------------------------------
70
110  之間怎麼隨機呢?  

int ss=(int)(71+Math.random()*(100-71+1));
   System.out.println(ss);

------------------------------------------
使用Calendar 處理時間格式

public static long parse(String dstr) {
if (dstr == null || dstr.length() == 0) {
return 0;
}
if (NumberUtils.isNumber(dstr)) {
return Long.parseLong(dstr) * 86400000;
}
String year = "";
String month = "";
String day = "";
int flag = 1;
char prech = 0;
dstr=dstr.trim();
for (char ch : dstr.toCharArray()) {
if (ch <= '9' && ch >= '0') {
switch (flag) {
case 1:
year += ch;
break;
case 2:
month += ch;
break;
case 3:
day += ch;
break;
}
} else {
if (prech <= '9' && prech >='0')
flag++;
}
prech = ch;

}
int y = year.equals("") ? 1970 : Integer.parseInt(year);
int m = month.equals("") ? 1 : Integer.parseInt(month);
int d = day.equals("") ? 1 : Integer.parseInt(day);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, y);
cal.set(Calendar.MONTH, m-1);
cal.set(Calendar.DAY_OF_MONTH, d);
return cal.getTimeInMillis();
}


-------------------------------
輸出任何格式的時間
擷取時間

public void InterceptionTime() {
    //
先製造一個完整的時間.
    DateFormat allTimeFormat = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date allTime = null;
    try {
      allTime =allTimeFormat.parse("2009-06-05 10:12:24.577");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    //
擷取時間,也可以使用下邊的SimpleDateFormat
    DateFormat format = newSimpleDateFormat("HH:mm:ss.SSS");
    String value = format.format(allTime);
    System.out.println(value);
   
    SimpleDateFormat  dateFormat = newSimpleDateFormat ("yyyy-MM-dd");
    String value2=dateFormat.format(allTime);
    System.out.println(value2);

  }
---------------------------------
轉換2進位制,
lang
包中Integer類中有個static String toBinaryString(int i)
----------------------------------------------
oracle
怎麼判斷表是否存在

select count(*) into num from USER_TABLES where TABLE_NAME='T2'
if num>0 then
  --
存在
end if;

------------------------------------------------------
記住帳號和密碼
JS   //   
cookie      
Cookie   user   =   new   Cookie("User_Name",   "hsyd");      
Cookie   pass   =   new   Cookie("Password",   "hsyd");      
response.addCookie(user);      
response.addCookie(pass);      
      
//   
cookie      
Cookie[]   cookies   =   request.getCookies();      
//   ...
找到匹配的cookie即可。  

相關文章