Java IO 一些基本操作
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裡面宣告java的jar
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即可。
相關文章
- 關於JAVA中順序IO的基本操作Java
- Java IO流操作Java
- Java 檔案 IO 操作Java
- Java IO的一些思考Java
- asm的一些基本操作ASM
- Java 檔案 IO 操作之 DirectIOJava
- 檔案 IO 操作的一些最佳實踐
- MVS DB 的一些基本操作
- java的IO操作:位元組流與字元流操作Java字元
- java string類 基本操作Java
- Java IO流字元流簡介及基本使用Java字元
- IO操作
- Java IO的基礎操作書目錄Java
- java資料庫操作基本流程Java資料庫
- MySQL對錶和庫的一些基本操作MySql
- JAVA的一些基本問題(轉)Java
- java安全編碼指南之:檔案IO操作Java
- 一文徹底弄懂Java的IO操作Java
- 詳解JAVA資料庫基本操作Java資料庫
- 並查集的一些基本概念以及基本操作(初始化,合併,查詢等操作)並查集
- java IO流 對檔案操作的程式碼集合Java
- 初識Java(Java陣列-陣列的基本操作)Java陣列
- 檔案IO操作
- Java IOJava
- ElasticSearch的Java Api基本操作入門指南ElasticsearchJavaAPI
- c++中的基本IOC++
- IO流下:位元組流、流操作規律(java基礎)Java
- [java IO流]之 IO概述Java
- [java IO流]之 基本資料型別輸入輸出流Java資料型別
- iOS檔案IO操作iOS
- IO流操作詳解
- Java IO1:IO和FileJava
- io的基本原理-nio
- java -IO流Java
- Java IO流Java
- java - IO流Java
- Java IO流Java
- Java IO: 流Java