Чтение содержимого из файла в J2ME
Я пытаюсь прочитать содержимое файла, но он не работает. Я просмотрел сеть и нашел разные реализации, как показано (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 ответ
ВЫПУСК: Ссылка на файл неверным способом
getResourceAsStream(...) предназначен для загрузки ресурсов из пути к классам либо из вашего двоичного пакета (.jar), либо из каталога classpath.
По сути, это означает, что для чтения файла из двоичного пакета используется метод getClass(). GetResourceAsStream(), а для чтения файла из физической памяти устройства - API-интерфейсы FileConnection.
Вы пытаетесь создать входной поток из файловой схемы типа, используемого в FileConnection, поэтому он не будет работать. Таким образом, чтобы решить вашу проблему, вы должны заменить инициализацию объекта inputtream в read(...)
, read2(...)
а также readFile(...)
с кодом ниже
InputStreamReader reader = new InputStreamReader(in);
//Вот in
является входным параметром метода типа InputStream
И в execute(...)
передать входной поток файлового соединения, как показано ниже
readFile(c.openInputStream());
//Вот c
является объектом типа FileConnection
,
Вы также можете рассмотреть их, если вы тестируете свое приложение в эмуляторе / устройстве.
- Убедитесь, что
System.getProperty("fileconn.dir.photos")
возвращает значение NON NULL - Файл хранится в соответствующем месте в системе