| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2422 人关注过本帖, 1 人收藏
标题:java常用基础技术,本人整理了一些,分享,会不断更新,并送大家一些积分
只看楼主 加入收藏
流星雨
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:JAVA风暴
等 级:版主
威 望:43
帖 子:1854
专家分:1868
注 册:2004-5-30
结帖率:56.76%
收藏(1)
已结贴  问题点数:0 回复次数:16 
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) {   
                filePath = new (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 {   
            new File(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 {   
            File filePath = new File(dir);// 查询路径   
            String[] files = filePath.list();// 存放所有查询结果   
            int i = 0;   
            for (i = 0; i < files.length; i++) {   
                new (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 {   
            File file = new File(filename.toString());   
            if (file.exists()) {   
                ret = true;   
            }   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
        return ret;   
    }  
-------------------------------------------------
根据制定路径,可以获取当前正在操作的文件的大小,容量为byte.
import
import
import
import


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


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


}

}
-------------------------------------------------------
如何用java获取网络文件的大小(多线程
import
import
import
import
import
import
import
import
import
import


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 = new BufferedInputStream(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 url;
    private long fileLength=0;
    //初始化线程数
    private int ThreadNum=5;
    public DownloadNetTest(){
    try{
       System.out.println("正在链接URL");
       url=new URL("http://211.64.201.201/uploadfile/nyz.mp3");
       HttpURLConnection urlcon=(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();
       String filename=trueurl.substring(trueurl.lastIndexOf('/')+1);
       fileOut=new File("D://",filename);
    }
    catch(MalformedURLException e){
       System.err.println(e);
    }
    catch(IOException e){
       System.err.println(e);
    }
    init();
 }
    private void init(){
       DownloadNetThread [] down=new DownloadNetThread[ThreadNum];
    try {
       for(int i=0;i<ThreadNum;i++){
          RandomAccessFile randOut=new RandomAccessFile(fileOut,"rw");
          randOut.setLength(fileLength);
          long block=fileLength/ThreadNum+1;
          randOut.seek(block*i);
          down[i]=new DownloadNetThread(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,long block,int threadId){
    this.url=url;
    this.randOut=out;
    this.block=block;
    this.threadId=threadId;
 }
  public void run(){
    try{
       HttpURLConnection http=(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:/Program Files/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 = new SimpleDateFormat("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 = new SimpleDateFormat("HH:mm:ss.SSS");
    String value = format.format(allTime);
    System.out.println(value);
   
    SimpleDateFormat  dateFormat = new SimpleDateFormat ("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 
2009-11-09 23:13
windizual
Rank: 3Rank: 3
等 级:论坛游侠
威 望:4
帖 子:124
专家分:186
注 册:2009-7-1
收藏
得分:2 
不错,这些资料整理得很好,的确是经常用的一些文件的操作

Java要学的东西好多~~~~~
2009-11-10 01:14
lampeter123
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:54
帖 子:2508
专家分:6424
注 册:2009-1-30
收藏
得分:2 
谢谢流星雨, YOU ARE MY IDOL!!!

你的优秀和我的人生无关!!!!
    
    我要过的,是属于我自己的生活~~~
2009-11-10 11:58
多多关照
Rank: 2
等 级:论坛游民
帖 子:42
专家分:51
注 册:2009-8-22
收藏
得分:5 
向版主们学习!
2009-11-10 13:25
【赣】暴风
Rank: 2
来 自:JAVA风暴
等 级:论坛游民
帖 子:11
专家分:20
注 册:2009-11-1
收藏
得分:5 
这些真都是基础么????
看的不是很懂诶。。。

好好学习。。。
天天向上!!!
2009-11-10 14:21
gameohyes
Rank: 16Rank: 16Rank: 16Rank: 16
来 自:湖南
等 级:版主
威 望:53
帖 子:1275
专家分:3629
注 册:2009-3-5
收藏
得分:2 
辛苦了

C#超级群 74862681,欢迎大家的到来!
2009-11-10 17:29
pywepe
Rank: 6Rank: 6
等 级:侠之大者
威 望:4
帖 子:296
专家分:483
注 册:2009-4-5
收藏
得分:2 
好样的 不愧为版主


java群
62635216
欢迎加入
2009-11-10 18:02
wsckt
Rank: 2
来 自:java风暴
等 级:论坛游民
帖 子:44
专家分:75
注 册:2009-10-20
收藏
得分:5 
IT姐就是好

喜欢灰太狼,喜欢它永不言败的精神!
喜欢java,喜欢它不需要理由!
2009-11-10 20:22
自JAVA风暴
Rank: 1
来 自:山东
等 级:新手上路
帖 子:8
专家分:5
注 册:2009-11-10
收藏
得分:5 
谢谢你了哥们
2009-11-10 23:33
windizual
Rank: 3Rank: 3
等 级:论坛游侠
威 望:4
帖 子:124
专家分:186
注 册:2009-7-1
收藏
得分:2 
回复 9楼 自JAVA风暴
流星雨是IT姐啦,呵呵

Java要学的东西好多~~~~~
2009-11-11 12:34
快速回复:java常用基础技术,本人整理了一些,分享,会不断更新,并送大家一些积分
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.035672 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved