读取文件的问题

来源:互联网 发布:打开照片的软件 编辑:程序博客网 时间:2024/05/16 08:37

import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.io.PrintStream;import java.io.PrintWriter;import java.net.URISyntaxException;import java.net.URL;public final class AccessTextFile {    /**     * 1. 演示将流中的文本读入一个 StringBuffer 中     * @throws IOException     */    public void readToBuffer(StringBuffer buffer, InputStream is)        throws IOException {        String line;        // 用来保存每行读取的内容        BufferedReader reader = new BufferedReader(new InputStreamReader(is));        line = reader.readLine();       // 读取第一行        while (line != null) {          // 如果 line 为空说明读完了            buffer.append(line);        // 将读到的内容添加到 buffer 中            buffer.append("\n");        // 添加换行符            line = reader.readLine();   // 读取下一行        }    }    public String readText(String text_url) throws IOException, URISyntaxException  {    /*File file = new File("../lxy/1.txt");    InputStream is = new FileInputStream(file);    */    //单独运行没问题     InputStream is = new FileInputStream(text_url);         StringBuffer buffer = new StringBuffer();         AccessTextFile atf = new AccessTextFile();         atf.readToBuffer(buffer, is);         String phones = new String(buffer);                 System.out.println(phones);     // 将读到 buffer 中的内容写出来         is.close();         return phones;     }    public static void main(String[] args) throws IOException, URISyntaxException {    AccessTextFile test = new AccessTextFile();    String text_url ="../lxy/1.txt";    test.readText(text_url);    }}

在windows系统上,如果单独运行一个java文件,其工程的位置如下, AccessTextFile

读取一个txt文档,File file = new File("../lxy/1.txt");
    InputStream is = new FileInputStream(file);

或者InputStream is = new FileInputStream(../lxy/1.txt);

与工程并排的一个包lxy下面的文件是能够读到的。

单独运行这个java文件其位置在工程放得位置

C:/Users/Admin1/git/WoShowAdmin/WoShowAdmin

C:/Users/Admin1/git/WoShowAdmin/lxy包放在这

但是当用jsp去调用这个类的时候,总是说找不到这个文件不知道为什么。

运行jsp工程时候,类的位置在tomca下对象的位置,可是也找不到。



在linix下写一个绝对路径是没有问题的InputStream is = new FileInputStream("/home/blog/apache-tomcat-5.5.27/webapps/WoShow_phones/")可以找到这个文件。


URL url = new URL(AccessTextFile.class.getClassLoader().getResource("")+"/config.properties") ;

    System.out.println(url);  
    File file = new File(url.toURI());

    System.out.println(url.toURI());

输出结果是:

file:/C:/Users/Admin1/git/WoShowAdmin/WoShowAdmin/WebRoot/WEB-INF/classes//config.properties
file:/C:/Users/Admin1/git/WoShowAdmin/WoShowAdmin/WebRoot/WEB-INF/classes//config.properties




原创粉丝点击