getAbsolutePath、getCanonicalPath、FileInputStream、FileOutputStream

来源:互联网 发布:dotamax数据更新 编辑:程序博客网 时间:2024/05/18 05:53
package fileStream;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


public class Test01 {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
String projectRootPath = new File("").getAbsolutePath();//获取项目路径

// String projectRootParentPath = new File("..").getCanonicalPath();
// File fileFolder = new File(projectRootParentPath+File.separator+"files");//规范路径名(将.以及..进行转换)
// if(!fileFolder.exists()){
// fileFolder.mkdir();
// }
// File file = new File(fileFolder.getCanonicalFile()+File.separator+"hello.txt");

File file = new File(projectRootPath+File.separator+"files"+File.separator+"hello.txt");
if(!file.exists()){
file.createNewFile();
}

//将字符串写入文件
String str = "hello world,my name is bing!";
byte[] bytes = str.getBytes();
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();

//从文本文件中读取内容
FileInputStream fis = new FileInputStream(file);
byte[] bytes2 = new byte[(int)file.length()];
fis.read(bytes2);
fis.close();
System.err.println(file.getCanonicalPath()+"\n"+new String(bytes2));
}


}
0 0
原创粉丝点击