java 对文件的操作

java 遍历文件夹文件:

package com.mixian.file;

import java.io.File;

public class getAllname {

	public static void main(String[] args) {
		File fileDir  = new File("c:/");
			File[] files = fileDir.listFiles();
			for(int i = 0; i<files.length ;i++){
				File file = files[i];
				if(file.isDirectory()){
					allFile(file);
				}else{
					System.out.println(file.getName());
				}
				
			}
		
	}
	
	public static void allFile(File dir){
		if(dir.isDirectory()){
			File[] files = dir.listFiles();
			for(int j=0;j<files.length;j++){
				System.out.println(files[j].getPath()+"/"+files[j].getName());
			}
		}else{
			System.out.println(dir.getPath()+"/"+dir.getName());
		}
	}
	
	

}

 将字节流读入到数组中:

package com.mixian.file;

import java.io.IOException;
import java.io.InputStream;

public class inStreamTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		InputStream is = System.in;
		byte[] bt = new byte[1024];
		try {
			 is.read(bt);  //将字节流读入到数组中
			 System.out.println("xx"+new String(bt).trim());
				is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

 

输出是类似的:

OutputStream out = System.out;
		try {
			out.write("12".getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

 读取文件信息:

try {
			FileInputStream is = new FileInputStream("c:/new.txt");
			int length;
			byte[] by = new byte[1024];
			try {
				while((length = is.read(by))!=-1){
					String str = new String(by,0,length);
					System.out.println(str);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

 文件写入:

File file = new File("c:/mixian.txt");
		if(!file.exists()){
			file.createNewFile();
		}
		
		FileOutputStream out = new FileOutputStream(file);
		byte[] byx = "test out".getBytes();
		out.write(byx);
		out.close();

 汉字的输入输出:

	//读取汉字的时候会出问题,因为一个汉字是占两个字节
		InputStreamReader isr = new InputStreamReader(System.in);
		char[] chars = new char[100];
		isr.read(chars);
		//int str = isr.read(chars);
		String str = new String(chars);
		System.out.println(str.trim());

 文件的读取:

//文件读取
		FileReader reader = new FileReader("c:/mixian.txt");
		int length;
		while((length = reader.read())!=-1){
			System.out.println((char)length);
		}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值