您的位置:首页 > 其它

?id=1454320074805

2016-02-01 23:52 127 查看

java读文件

项目的文件夹结构:



项目相对路径——适用于demo

在Java开发工具的project中使用相对路径,路径不以“/”开头,在project中,相对路径的根目录是project的根文件夹。

* 若文件在java目录下:

File f = new File(“src/com/test/a.txt”);

* 若文件在resources目录下:

File f = new File(“src/main/resources/b.txt”);

注意:

脱离了IDE环境,这个写法就是错误的,也并非每个IDE都如此,但我见到的都是这样的。

不推荐该种写法,因为一般打包后的项目结构跟开发的工程结构不同,打包后java和resources下的文件都会被挪到classes目录,classes目录即classpath


CLASSPATH——适用于需要发布的项目

classpath是java字节码所在的路径,包括本身项目的classes文件和jar包里的文件。

/**
* Created by tanglin on 2016/1/27.
* 通过相对路径和classpath加载文件
*/
public class FileReaderLine {
private static String fileName = "src/main/resources/data.txt";

public static void main(String[] args) {
readFromClasspath();
readFromRelativePath();
}

public static void readFromRelativePath(){
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
public static void readFromClasspath(){
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
InputStream is = FileReaderLine.class.getClassLoader().getResourceAsStream("data.txt");
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
System.out.println(tempString);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: