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 {
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 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 {
File file = 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 = 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 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 = 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 java.net.URL 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即可。
-----------------------------------------------------------------
----------------解决方案--------------------------------------------------------
不错,这些资料整理得很好,的确是经常用的一些文件的操作
----------------解决方案--------------------------------------------------------
谢谢流星雨, YOU ARE MY IDOL!!!
----------------解决方案--------------------------------------------------------
向版主们学习!
----------------解决方案--------------------------------------------------------
这些真都是基础么????
看的不是很懂诶。。。
----------------解决方案--------------------------------------------------------
辛苦了
----------------解决方案--------------------------------------------------------
好样的 不愧为版主
----------------解决方案--------------------------------------------------------
IT姐就是好
----------------解决方案--------------------------------------------------------
谢谢你了哥们
----------------解决方案--------------------------------------------------------
回复 9楼 自JAVA风暴
流星雨是IT姐啦,呵呵 ----------------解决方案--------------------------------------------------------