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);
}