一、标准的输入流 System.in
--------------------------------------------------
1.类型是InputStream
@Test
public void tsSystemIn() throws Exception
{
InputStream is = System.in;
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line = br.readLine()) != null){
if(line.equals("quit")){
System.exit(-1);
}
System.out.println("hello:" + line);
}
}
二、标准的输出流System.out
---------------------------------------------------
1.System.out 的类型是PrintStream, 是OutputStream的子类的子类
@Test
public void tsSystemOut() throws Exception{
System.setOut(new PrintStream(new FileOutputStream("d:\\a.txt")));
System.out.println("xxxxxxxxxxxxxxxxxx");
}
三、File类,对目录或者文件的封装
---------------------------------------------------
1.isDirectory();
2.exists();
3.isFile();
4.mkdir() / mkdirs() : 创建一级 / 多级目录
5.creatNewFile();
6.listFiles();
7.getCanonicalPath() : 标准的,规范的路径
8.getAbsolutePath() : 绝对路径
四、递归输出D盘下的所有文件和文件夹
----------------------------------------------------
@Test
public void tsScanFiles()
{
List<String> fileList = new ArrayList<String>();
List<String> folderList = new ArrayList<String>();
scanFiles("D:\\test",fileList,folderList);
for(String s : fileList)
{
System.out.println("file : " + s);
}
for(String s : folderList)
{
System.out.println("folder : " + s);
}
}
/**
* 浏览指定路径下的所有文件和文件夹
* @param desPath
* @param fileList
* @param folderList
*/
public void scanFiles(String desPath , List<String> fileList,List<String> folderList)
{
File file = new File(desPath);
File [] fs = file.listFiles();
for(File f0 : fs)
{
if(f0.isFile()) /*如果是文件*/
{
fileList.add(f0.getAbsolutePath());
}
else
{
folderList.add(f0.getAbsolutePath());
scanFiles(f0.getAbsolutePath(),fileList,folderList);
}
}
}
五、实现文件夹的复制
----------------------------------------------------
@Test
public void tsCopyFolder()
{
copyFolder("D:\\test" , "F:\\ccc");
}
/**
* 拷贝文件夹
* @param src
* @param des
*/
public void copyFolder(String src,String des)
{
File file = new File(src);
String rootFolderName = file.getName();
des = des + "\\" + rootFolderName;
copyFolder_1(src,des);
}
public void copyFolder_1(String src,String des)
{
File file = new File(src);
File [] fs = file.listFiles();
for(File f0 : fs)
{
if(f0.isFile()) /*如果是文件*/
{
copyFile(f0.getAbsolutePath(),des + "\\" + f0.getName());
}
else
{
String path = des + "\\" + f0.getName();
File f = new File(path);
f.mkdirs();
copyFolder_1(f0.getAbsolutePath(),path);
}
}
}
/**
* 复制文件
* @param src
* @param des
*/
public void copyFile(String src,String des)
{
try {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(des);
byte [] buf = new byte[1024];
int len = 0;
while((len = fis.read(buf)) != -1)
{
fos.write(buf);
}
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}