获取 路径n中方法和方式 + 文件的读取。。


http://blog.csdn.net/snannan_268/article/details/5511614

另外:System.getProperty()中的字符串参数如下: 
System.getProperty()参数大全 
# java.version                                Java Runtime Environment version

比如当前的路径为 C:/test : 
File directory = new File("abc"); 
directory.getCanonicalPath(); //得到的是C:/test/abc 
directory.getAbsolutePath();    //得到的是C:/test/ab

(1)类的绝对路径:Class.class.getClass().getResource("/").getPath() 
结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/ 
(2)得到工程的路径:System.getProperty("user.dir")
3.在Servlet中取得路径: 

(1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。 
结果:E:/Tomcat/webapps/TEST 
(2)得到IE地址栏地址:request.getRequestURL() 
结果:http://localhost:8080/TEST/test 
(3)得到相对地址:request.getRequestURI() 
结果:/TEST/test

public class FileTest {
	public static void main(String[] args) {
//		 String infname="G:\\test.txt";     //默认的输入文件名
// String curpath = Class.class.getClass().getResource("/").getPath();
		String s=null; 
	        try{ 
	            File fin = new File("");        //转入的文件对象
	            //addre
	            System.out.println(fin.getAbsolutePath());
	            System.out.println(fin.getCanonicalPath());
	            InputStreamReader read = new InputStreamReader(new FileInputStream(fin),"gbk");
	            
	            BufferedReader in = new BufferedReader(read);  //打开输入流
	            while((s = in.readLine()) != null){
	            	//读字符串
	                System.out.println(s);          //写出
	            } 
	            in.close(); //关闭缓冲读入流及文件读入流的连接     
	        }catch (FileNotFoundException e1){           //异常处理
	            e1.printStackTrace();
	        }catch(IOException e2){    
	            e2.printStackTrace();
	        } 
	    } 
}File 其它常用的方法:

       

// 创建文件,如果文件不存在,创建 true 如果文件存在,则不创建 false。 如果路径错误,IOException。

boolean b1 = file.createNewFile();

//-----------删除文件操作-------注意:不去回收站。慎用------

 boolean b2 = file.delete();

//mkdir()创建单个目录。//dir.mkdirs();创建多级目录

boolean b4 = dir.mkdir();

//删除目录时,如果目录中有内容,无法直接删除。

boolean b5 = dir.delete();

// f.mkdir();//f.createNewFile();
2. listFiles() 方法介绍

File dir = new File("e:\\java_code");

//获取的是目录下的当前的文件以及文件夹的名称。

String[] names = dir.list();

for(String name : names){

System.out.println(name);

}

//文件过滤器

File file = new File("E:\\code\\day11_code");

//获取指定扩展名的文件,由于要对所有文件进行扩展名筛选,因此调用方法需要传递过滤器

File[] files = file.listFiles(new MyFileFilter());//也可直接写new FilenameFilter 重写里面的方法。

//遍历获取到的所有符合条件的文件

for (File f : files) {

System.out.println(f);

自定类继承FilenameFilter过滤器接口

//定义类实现文件名称FilenameFilter过滤器

class MyFileFilter implements FilenameFilter{

public boolean accept(File dir, String name) {

return name.endsWith(".java");

}

自定义类继承FileFilter过滤器接口

//文件过滤器

class FileFileterByDir implements FileFilter{

public boolean accept(File pathname) {

return pathname.isDirectory();

}

递归使用,自身调自身, 最简单的方法:

public static void main(String[] args) {

//计算1~num的和,使用递归完成

int n = 5;int sum = getSum(n);

System.out.println(sum);

}

public static int getSum(int n) {

if(n == 1)return 1;

return n + getSum(n-1);//停留点,数据计算点

}

编写一个方法用来打印指定目录中的文件路径,并进行方法的调用

File file = new File("d:\\test");

public static void getFileAll(File file) {

File[] files = file.listFiles(); // 这里同样可以传入一个文件/文件名过滤器 file.listFiles(MyFileFilter());

//遍历当前目录下的所有文件和文件夹

for (File f : files) {

//判断当前遍历到的是否为目录

if(f.isDirectory()){

//是目录,继续获取这个目录下的所有文件和文件夹

getFileAll(f);

}else{

//不是目录,说明当前f就是文件,那么就打印出来

System.out.println(f);

}

public boolean exists() 判断File对象对应的文件或文件夹是否存在

public String getAbsolutePath() 获取当前File的绝对路径

public String getName() 获取当前File对象的文件或文件夹名称

public long length() 获取当前File对象的文件或文件夹的大小(字节)

///

输出流中定义都是写write方法(还有close flush )

//in or out ,you just think youself is a computer ,for hard disk or memory you ,read or write ,input or output ;

// and machine could read byte directly

字节输出流 outputStream write(byte[] b) write(byte[] b,int off ,int len) 子类 FileOutputStream //需求:将数据写入到文件中

File file = new File("c:\\file.txt");

FileOutputStream fos = new FileOutputStream(file);// 文件续写数据FileOutputStream fos = new FileOutputStream(file, true);

byte[] data = "abcde".getBytes(); //换行:String str = "\r\n"+"itcast";

///\r'是回车,'\n'是换行,前者使光标到行首,后者使光标下移一格。通常:Enter是两个加起来

fos.write(data);

fos.close();

字节输入流: int read() read(byte[] b)

InputStream此抽象类是表示字节输入流的所有类的超类

int read():读取一个字节并返回,没有字节返回-1. int read(byte[]): 读取一定量的字节数,并存储到字节数组中,返回读取到的字节数

读取数据read(byte[])方法

File file = new File("c:\\file.txt");

// 创建一个字节输入流对象,必须明确数据源,其实就是创建字节读取流和数据源相关联。

FileInputStream fis = new FileInputStream(file);

//创建一个字节数组。

byte[] buf = new byte[1024];//长度可以定义成1024的整数倍。

int len = 0;

while((len=fis.read(buf))!=-1){

System.out.println(new String(buf,0,len));

}

fis.close();

字符:

编码表:其实就是生活中字符和计算机二进制的对应关系表。

1、ascii: 一个字节中的7位就可以表示。对应的字节都是正数。0-xxxxxxx

2、iso-8859-1:拉丁码表 latin,用了一个字节用的8位。1-xxxxxxx  负数。

3、GB2312:简体中文码表。包含6000-7000中文和符号。用两个字节表示。两个字节第一个字节是负数,第二个字节可能是正数

GBK:目前最常用的中文码表,2万的中文和符号。用两个字节表示,其中的一部分文字,第一个字节开头是1,第二字节开头是0

1、unicode:国际标准码表:无论是什么文字,都用两个字节存储。

Java中的char类型用的就是这个码表。char c = 'a';占两个字节。

Java中的字符串是按照系统默认码表来解析的。简体中文版 字符串默认的码表是GBK

UTF-8:基于unicode,一个字节就可以存储数据,不要用两个字节存储,而且这个码表更加的标准化,在每一个字节头加入了编码信息

//https://www.oschina.net/code/snippet_142385_4297 // 把中文字符串转换------->>为十六进制Unicode编码字符串

//读入

FileReader fr = new FileReader("D:\\test\\cn.txt");

int ch = 0;

while((ch = fr.read())!=-1){

//输出字符本身

System.out.println((char)ch);

//写入

FileWriter fw = new FileWriter("d\\text\\fw.txt");

fw.close();

//r任务:copy file

//1,明确源和目的。

FileReader fr = new FileReader("c:\\cn.txt");

FileWriter fw = new FileWriter("c:\\copy.txt");

//2,为了提高效率。自定义缓冲区数组。字符数组。

char[] buf = new char[1024];

int len = 0;

while((len=fr.read(buf))!=-1){

fw.write(buf,0,len);}

IO流的分类 |- 字节流     |- 字节输入流 InputStream 抽象类         |-  FileInputStream 操作文件的字节输入流 |- 字节输出流 OuputStream抽象类     |- FileOutputStream 操作文件的字节输出流 |- 字符流     |- 字符输入流 Reader抽象类         |- InputStreamReader 输入操作的转换流             |- FileReader 用来操作文件的字符输入流(简便的流)     |- 字符输出流 Writer抽象类         |- OutputStreamWriter 输出操作的转换流             |- FileWriter 用来操作文件的字符输出流(简便的流)

其它:

OutputStreamWriter //程序输出到磁盘当然是字符变成字节,

将字符串按照指定的编码表转成字节,在使用字节流将这些字节写出去

InputStreamReader

它使用指定的字符编码表读取字节,并将其解码为字符 //程序读,从磁盘到程序。

//创建与文件关联的字节输出流对象

FileOutputStream fos = new FileOutputStream("c:\\cn8.txt");

//创建可以把字符转成字节的转换流对象,并指定编码

OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");------<<<<<<<<<<< 输出,字符变字节

//调用转换流,把文字写出去,其实是写到转换流的缓冲区中

osw.write("你好");//写入缓冲区。

osw.close();

InputStream in = new FileInputStream("c:\\cn8.txt");

//创建转换流对象

//InputStreamReader isr = new InputStreamReader(in);这样创建对象,会用本地默认码表读取,将会发生错误解码的错误

        InputStreamReader isr = new InputStreamReader(in,"utf-8");-------<<<<<<<<<<输入,字节变字符

//使用转换流去读字节流中的字节

int ch = 0;

while((ch = isr.read())!=-1){

System.out.println((char)ch);

}

//关闭流

isr.close();

什么时候用子类呢? FileReader FileWriter

条件:

1、操作的是文件。2、使用默认编码。

//缓冲流

字节缓冲输出流

FileOutputStream fileOut = new FileOutputStream("abc.txt");

//使用高效的流,把基本的流进行封装,实现速度的提升

BufferedOutputStream out = new BufferedOutputStream(fileOut);

//2,写数据

out.write("hello".getBytes());

//3,关闭流

out.close();

字节缓冲输入流

FileInputStream fileIn = new FileInputStream("abc.txt");

//把基本的流包装成高效的流

BufferedInputStream in = new BufferedInputStream(fileIn);

//2,读数据

int ch = -1;

while ( (ch = in.read()) != -1 ) {

//打印

System.out.print((char)ch);

}

高效的流完成复制文件

    private static void method4(String src, String dest) throws IOException {         //1,指定数据源         BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));          //2,指定目的地         BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));          //3,读数据         byte[] buffer = new byte[1024];         int len = -1;         while ( (len = in.read(buffer)) != -1) {             //4,写数据             out.write(buffer, 0, len);         }          //5,关闭流         in.close();         out.close(); 2.2字符缓冲流 字符缓冲输入流 BufferedReader 字符缓冲输出流 BufferedWriter

将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入

void newLine() 根据当前的系统,写入一个换行符

        //基本字符输出流         FileWriter fileOut = new FileWriter("file.txt");         //把基本的流进行包装         BufferedWriter out = new BufferedWriter(fileOut);         //2,写数据         for (int i=0; i<5; i++) {             out.write("hello");             out.newLine();         }         //3,关闭流         out.close();

从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

方法

public String readLine() 读取一个文本行包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null

        BufferedReader in = new BufferedReader(new FileReader("file.txt"));         //2,读数据         //一次一个字符         //一次一个字符数组         //一次读取文本中一行的字符串内容         String line = null;         while( (line = in.readLine()) != null ){             System.out.println(line);         }

        //1,指定数据源, 是数据源中读数据,采用输入流         BufferedReader in = new BufferedReader(new FileReader("file.txt"));         //2,指定目的地,是把数据写入目的地,采用输出流         BufferedWriter out = new BufferedWriter(new FileWriter("copyFile.txt"));         //3,读数据         String line = null;         while ( (line = in.readLine()) != null ) {             //4,写数据             out.write(line);             //写入换行符号             out.newLine();         }         //5,关闭流         out.close();         in.close();

方法: 读数据方法: read() 一次读一个字节或字符的方法 read(byte[]  char[]) 一次读一个数组数据的方法 readLine() 一次读一行字符串的方法(BufferedReader类特有方法) readObject() 从流中读取对象(ObjectInputStream特有方法) 写数据方法: write(int) 一次写一个字节或字符到文件中 write(byte[] char[]) 一次写一个数组数据到文件中 write(String) 一次写一个字符串内容到文件中 writeObject(Object ) 写对象到流中(ObjectOutputStream类特有方法) newLine() 写一个换行符号(BufferedWriter类特有方法) 从文件中读数据的过程 1,创建输入流对象 2,从文件中读数据 3,关闭输入流 文件复制的过程 1,创建输入流(数据源) 2,创建输出流(目的地) 3,从输入流中读数据 4,通过输出流,把数据写入目的地 5,关闭流



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值