在J2ME中从文件中读取内容

时间:2011-12-12 11:09:27

标签: java file-io java-me midp file-connection

我正在尝试阅读文件的内容,但似乎无法正常工作。我在网上浏览并找到了不同的实现,如图所示(read(),read2(),readLine()),但每次运行代码时,它们都会给出NullPointer异常。请问我该怎么做才能解决这个问题。

     private String folder;
        static String filename;
        //IMPLEMENTATION 1
        private void readFile(String f) {
            try {
                InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream(f));
                String line = null;
                while ((line = readLine(reader)) != null) {
                    System.out.println(line);
                }
                reader.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
/**
         * Reads a single line using the specified reader.
         * @throws java.io.IOException if an exception occurs when reading the
         * line
         */
        private String readLine(InputStreamReader reader) throws IOException {
            // Test whether the end of file has been reached. If so, return null.
            int readChar = reader.read();
            if (readChar == -1) {
                return null;
            }
            StringBuffer string = new StringBuffer("");
            // Read until end of file or new line
            while (readChar != -1 && readChar != '\n') {
                if (readChar != '\r') {
                    string.append((char) readChar);
                }
                // Read the next character
                readChar = reader.read();
            }
            return string.toString();
        }

        //IMPLEMENTATION 2
        private String read(String file) throws IOException {
            InputStream is = getClass().getResourceAsStream(file);
            StringBuffer sb = new StringBuffer();
            int chars, i = 0;
            while ((chars = is.read()) != -1) {
                sb.append((char) chars);
            }
            return sb.toString();
        }

        //IMPLEMENTATION 3
        private String read2(String file) throws IOException {
            String content = "";
            Reader in = new InputStreamReader(this.getClass().getResourceAsStream(file));
            StringBuffer temp = new StringBuffer(1024);
            char[] buffer = new char[1024];
            int read;
            while ((read = in.read(buffer, 0, buffer.length)) != -1) {
                temp.append(buffer, 0, read);
            }
            content = temp.toString();
                    return content;
        }

        public void execute() throws IOException {
            folder = System.getProperty("fileconn.dir.photos") + "mcast/";
            String path = folder + filename + ".txt";
            FileConnection c = (FileConnection) Connector.open(path, Connector.READ_WRITE);

            try {
                // Checking if the directoy exists or not. If it doesn't exist we create it.
                if (c.exists()) {
            readFile(path);
                    //read(path);
                   // read2(path);
                    System.out.println(read(path));
                } else {
                    System.out.println(filename + ".txt does not exist. Please specify a correct file name");
                }
            } finally {
                c.close();
            }
        }

private String readLine(InputStreamReader reader) throws IOException {
        // Test whether the end of file has been reached. If so, return null.
        int readChar = reader.read();
        if (readChar == -1) {
            return null;
        }
        StringBuffer string = new StringBuffer("");
        // Read until end of file or new line
        while (readChar != -1 && readChar != '\n') {
            // Append the read character to the string. Some operating systems
            // such as Microsoft Windows prepend newline character ('\n') with
            // carriage return ('\r'). This is part of the newline character
            // and therefore an exception that should not be appended to the
            // string.
            if (readChar != '\r') {
                string.append((char) readChar);
            }
            // Read the next character
            readChar = reader.read();
        }
        return string.toString();
    }


    }

1 个答案:

答案 0 :(得分:2)

问题 使用错误的方法引用文件

getResourceAsStream(...)用于从二进制包(.jar)或类路径目录中加载类路径中的资源。

所以它本质上意味着,从二进制包中读取文件使用getClass()。getResourceAsStream(),并且从设备的物理内存中读取文件使用FileConnection API。

您正在尝试从FileConnection中使用的类型的文件架构创建输入流,因此它将无法工作。因此,为了解决您的问题,您已使用以下代码替换read(...)read2(...)readFile(...)中的输入流对象初始化

InputStreamReader reader = new InputStreamReader(in); //此处in是InputStream类型的方法输入参数

并在execute(...)中传递文件连接输入流,如下所示

readFile(c.openInputStream()); //此处c是FileConnection类型的对象

如果您在模拟器/设备中测试应用程序,您可能还需要考虑这些

  1. 确保System.getProperty("fileconn.dir.photos")返回 非空
  2. 文件存储在系统中的适当位置