我必须使用servlet读取文件。这是我使用的代码。但是文件没有使用此代码读取。始终打印File contains null value-----------------
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("text/html");
String filename = "D/root.properties";
ServletContext context = getServletContext();
InputStream inp = context.getResourceAsStream(filename);
if (inp != null) {
InputStreamReader isr = new InputStreamReader(inp);
BufferedReader reader = new BufferedReader(isr);
PrintWriter pw = response.getWriter();
String text = "";
while ((text = reader.readLine()) != null) {
}
} else {
System.out.println("File contains null value-----------------");
}
} catch(Exception e) {
System.out.println("Rxpn............................................."+e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
答案 0 :(得分:4)
javadoc救援:
java.net.URL getResource(java.lang.String path) 抛出java.net.MalformedURLException
返回映射到给定路径的资源的URL。
路径必须以/开头,并且被解释为相对于当前上下文根,或相对于/ META-INF / resources目录 Web应用程序的/ WEB-INF / lib目录中的JAR文件。 此方法将首先搜索Web应用程序的文档根目录 对于请求的资源,在搜索任何JAR文件之前 在/ WEB-INF / lib中。 JAR文件内部的顺序 搜索/ WEB-INF / lib未定义。
如果要从Web应用程序中的资源中读取,请使用上面指示的路径。如果要从文件系统中读取,请使用文件IO(和正确的文件名):new FileInputStream("D:/root.properties")
答案 1 :(得分:0)
使用以下代码。 有了它,你可以阅读文件
File file = new File("Filepath");
try {
if (file.exists()) {
BufferedReader objBufferReader = new BufferedReader(
new FileReader(file));
ArrayList<String> arrListString = new ArrayList<String>();
String sLine = "";
int iCount = 0;
while ((sLine = objBufferReader.readLine()) != null) {
arrListString.add(sLine);
}
objBufferReader.close();
for (iCount = 0; iCount < arrListString.size(); iCount++) {
if (iCount == 0) {
createTable(arrListString.get(iCount).trim());
} else {
insertIntoTable(arrListString.get(iCount).trim());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
答案 2 :(得分:0)
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream file = new FileInputStream("c:\\hi.txt");
DataInputStream input = new DataInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String text = "";
while ((text = br.readLine()) != null) {
System.out.println(text);
}
}
}
请尝试以上代码示例。我认为在您的代码中,找不到文件。请在上面的代码中给出文件路径并尝试。