我的代码有什么问题吗?我是Java的新手,我正在尝试将文件导入MongoDB。但是有一个错误,我不知道它是什么。我正在使用Eclipse。
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
public class readwrite {
public static void main(String[] args) throws FileNotFoundException,IOException,JSONParseException{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("actualdata");
DBCollection collection = db.getCollection("metadata");
String line = null;
StringBuilder sb = new StringBuilder();
try {
FileInputStream fstream = null;
try {
fstream = new FileInputStream("/home/Output/json1-100000-all");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File does not exist, exiting");
return;
}
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(fstream));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
DBObject dbObject;
sb.append(dbObject = (DBObject) JSON.parse(bufferedReader.readLine()));
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file");
}
catch(IOException ex) {
System.out.println(
"Error reading file");
}
}
}
这是显示的错误
[
Exception in thread "main" com.mongodb.util.JSONParseException:
{
^
at com.mongodb.util.JSONParser.read(JSON.java:272)
at com.mongodb.util.JSONParser.parseObject(JSON.java:230)
at com.mongodb.util.JSONParser.parse(JSON.java:195)
at com.mongodb.util.JSONParser.parse(JSON.java:145)
at com.mongodb.util.JSON.parse(JSON.java:81)
at com.mongodb.util.JSON.parse(JSON.java:66)
at readwrite.main(readwrite.java:45)
当我点击com.mongodb.util.JSONParser.read(JSON.java:272)时,它会显示此错误,其中显示未找到Source。源附件不包含文件JSON.class的源。 如果我没有包含DBObject的转换,我可以打印BufferedReader的输出。提前谢谢!
答案 0 :(得分:0)
1)你不是要写JSON.parse(线) 而不是JSON.parse(bufferedReader.readLine()))? 这可能导致它尝试在最后一次迭代时解析'null'
2)如果这没有帮助,你能否在失败的迭代中获得'line'的确切字符串值? (这应该很容易使用调试器或简单打印到系统)
此致