文件读取需要找到文件具体在什么地方,有相对路径和绝对路径;
绝对路径就是相对于操作系统的路径,比如在windows下的D:\XX\file.txt;
相对路径则是针对想在运行的项目环境的路径,可以执行类可以通过项目所在的容器环境找到文件;
相对路径简单可以分为两种情况:
一、从项目根目录下寻找
File file = new File("conf/mixpanel.xml"); FileInputStream fi = new FileInputStream("conf/log4j.properties");
二、通过ClassLoader利用类加载的加载路径进行寻找
AppTest.class.getClassLoader().getResourceAsStream("config.xml");
AppTest.class.getClassLoader().getResource("config.xml");
/**
* Finds the resource with the given name. A resource is some data
* (images, audio, text, etc) that can be accessed by class code in a way
* that is independent of the location of the code.
*
* <p> The name of a resource is a '<tt>/</tt>'-separated path name that
* identifies the resource.
*
* <p> This method will first search the parent class loader for the
* resource; if the parent is <tt>null</tt> the path of the class loader
* built-in to the virtual machine is searched. That failing, this method
* will invoke {@link #findResource(String)} to find the resource. </p>
*
* @param name
* The resource name
*
* @return A <tt>URL</tt> object for reading the resource, or
* <tt>null</tt> if the resource could not be found or the invoker
* doesn't have adequate privileges to get the resource.
*
* @since 1.1
*/
public URL getResource(String name) {
URL url;
if (parent != null) {
url = parent.getResource(name);
} else {
url = getBootstrapResource(name);
}
if (url == null) {
url = findResource(name);
}
return url;
}
文件输出:
FileOutputStream fos = new FileOutputStream(""); fos.write(CellUtil.cloneQualifier(cell)); fos.write(Bytes.toBytes("=")); fos.write(CellUtil.cloneValue(cell)); fos.write(Bytes.toBytes("\r\n")); fos.close();
如果文件输出的路径不存在,需要进行创建;