方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
方式二:采用ResourceBundle类读取配置信息,
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。缺点:只能加载类classes下面的资源文件且只能读取.properties文件。
package filewriter
import java.io.FileWriter
import java.io.IOException
public class IOExceptionDemo {
private static final String LINE_SEPARATOR = System.getProperty("line.separator")
public static void main(String[] args) {
FileWriter fw = null
try {
fw = new FileWriter("k:\\Demo.txt", true)
fw.write("hello" + LINE_SEPARATOR + "world!")
} catch (Exception e) {
System.out.println(e.toString())
} finally {
if (fw != null)
try {
fw.close()
} catch (IOException e) {
throw new RuntimeException("关闭失败!")
}
}
}
}
创建文件new File(文件路径).createNewFile()这是写入文件
try{
FileOutputStream filewrite = new FileOutputStream(文件路径)//这个要捕捉异常
filewrite.write(要写入的数据byte[])
filewrite.close()
}catch(IOException e)