fileWriterSrv = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempDir), "UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(tempDir),"GBK"), 30 * 1024 * 1024);
public class InsertContent {
private String filePath;
private String content;
private long position;
public InsertContent(String path, String con, long pos) {
filePath = path;
content = con;
position = pos;
}
public void setFilePath(String path) {
filePath = path;
}
public void setContent(String con) {
content = con;
}
public void setPosition(long pos) {
position = pos;
}
public void insertCon(){
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filePath, "rw");
raf.seek(position);
StringBuffer sb = new StringBuffer();
int len;
sb.append("123");
sb.append("456");
byte[] b = new byte[100];
while( (len=raf.read(b)) != -1 ) {
sb.append( new String(b, 0, len) );
}
raf.seek(position);
raf.write( content.getBytes("UTF-8") );
raf.write( sb.toString().getBytes("UTF-8") );
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
InsertContent ic = new InsertContent("D:\\rpt\\number\\00010000\\file1.txt", "mio", 0);
ic.insertCon();
}
}
public boolean creatTxt(){
boolean falg = false;
try {
SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) ApplicationContextHelper.getBean("testSqlSessionFactory");
SqlSession sqlSession = sqlSessionFactory.openSession();
Cursor<User> cursor = sqlSession.selectCursor("com.example.study.dao.UserMapper.selectAll");
Iterator<User> iterator = cursor.iterator();
RandomAccessFile raf = null;
String four = null;
StringBuffer sb = null;
String stauts = null;
while (iterator.hasNext()){
User user = iterator.next();
if (!user.getMobilefour().equals(four)){
if (null != raf){
raf.seek(0);
raf.write("定位到第一行\r\n".getBytes("UTF-8"));
raf.write(sb.toString().getBytes("UTF-8"));
raf.close();
}
String fileName = rptDir + "/" + user.getMobilefour()+".txt";
File file = new File(fileName);
if (file.exists())
file.delete();
if (!file.exists())
file.createNewFile();
logger.info("文件生成路径:" + fileName);
raf = new RandomAccessFile(fileName, "rw");
four = user.getMobilefour();
sb = new StringBuffer();
String title = String.format("%s\r\n",user.getMobilefour().trim());
sb.append(title);
}
stauts = "1".equals(user.getStauts()) ? "在线" : "消失";
String body = String.format("%s|%s|%s|%s\r\n",
user.getName(),
user.getEmail(),
user.getSex(),
stauts);
sb.append(body);
}
raf.seek(0);
raf.write("定位到第一行\r\n".getBytes("UTF-8"));
raf.write(sb.toString().getBytes("UTF-8"));
raf.close();
falg = true;
}catch (Exception e){
logger.info("失败",e);
falg =false;
}
return falg;
}