以下是我阅读和拆分文本文件内容的代码。
try {
br = new BufferedReader(new FileReader("F:\\Test.txt"));
final char[] cbuf = new char[2048];
final int length = br.read(cbuf);
cbuf[length] = '@';
String packet = new String(cbuf, 0, length + 1);
final String[] splitedPacket=packet.split("@");
for(int i=0;i<splitedPacket.length;i++)
{
if(splitedPacket[i].contains("POS"))
{
System.out.println(splitedPacket[i]+"@");
preparedstatement=connection.prepareStatement("insert into inserttextfile([file]) values(?)");
preparedstatement.setString(1, splitedPacket[i]+"@");
preparedstatement.executeUpdate();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
在我的小尺寸.txt文件中工作正常,但如果我使用超过30 MB的文本文件,我会得到数组索引超出绑定的异常。
那么如何拆分和读取这种.txt文件并插入数据库? (特别希望拆分大尺寸文件(例如从30 MB开始像5 MB)并插入数据库) 请在这个问题上指导我。
答案 0 :(得分:2)
通过不使用readLine
,你很难做到这一点 try {
FileInputStream fis = new FileInputStream("F:\\Test.txt");
reader = new BufferedReader(new InputStreamReader(fis));
String line = reader.readLine();
while(line != null){
//process your line here, it's just a String...
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
...
} catch (IOException ex) {
答案 1 :(得分:2)
try (Scanner read = new Scanner(new File("/tmp/datafile.txt"));) {
read.useDelimiter("@");
while (read.hasNext()) {
String splitedPacket = read.next();
System.out.println(splitedPacket);
// Perform DB Operation
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}