Um grande lote de dados era necessário há algum tempo. O DBA forneceu arquivos CVS, mas cada arquivo CVS tem vários GB de tamanho, por isso é carregado diretamente. O banco de dados é muito lento e causará memória insuficiente. Para cumprir essa função, um programa para dividir rapidamente os arquivos foi escrito.
importar org.apache.log4j.logmanager; importar org.apache.log4j.logger; importar java.io.*; importar java.util.*; importar java.util.concurrent.*; classe pública filesplitutil {private final estático logger log = logManager.getLogger (filesplitutil.class); private estático final Longo OriginFilesize = 1024 * 1024 * 100; // 100m estático privado final Int BlockFilesize = 1024 * 1024 * 64; // Para impedir que os chineses sejam iluminados, você deve levar 2 para o n Power/ ** * CVS Separator de arquivos */ private estático char cvSseparator = '^'; public static void main (string args []) {long start = system.currenttimemillis (); tente {string filename = "d: //csvtest//aa.csv"; Arquivo fontefile = novo arquivo (nome do arquivo); if (Sourcefile.Length ()> = OriginFilesize) {String cvsFilename = filename.Replaceall ("////", "/"); Filesplitutil filesplitUtil = new FileSplitUtil (); List <String> partes = filesplitutil.splitbysize (cvsfilename, blockfilesize); para (parte da string: partes) {System.out.println ("PartName é:"+parte); }} System.out.println ("Comprimento total do arquivo" + fontefile.length () + ", tempo para dividir o arquivo:" + (System.currenttimemillis () - start) + "ms."); } catch (Exceção e) {log.info (e.getStackTrace ()); }} / *** Arquivo dividido** @Param FileName O nome completo do arquivo a ser dividido* @param bytesize dividido por quantos bytes* @return Lista de nomes de arquivos divididos* / list public <String> splitBysize (string filename, int bytesize) Throws IoException, intercepException {list <tumname, parques = strings). Arquivo de arquivo = novo arquivo (nome do arquivo); int count = (int) math.ceil (file.length () / (duplo) bytesize); int countlen = (count + "") .Length (); RAF RAFACESSFILE RAF = novo RandomAccessFile (nome do arquivo, "r"); totallen longo = raf.length (); CountdownLatch Latch = new CountdownLatch (contagem); for (int i = 0; i <count; i ++) {string partfilename = file.getPath ()+"." + leftpad ((i + 1) + "", countlen, '0') + ".cvs"; int readsize = bytesize; startpos longo = (longo) i * bytesize; Long NextPos = (longo) (i+1) * Bytesize; if (nextPos> Totallen) {readsize = (int) (Totallen-startPos); } novo Splitrunnable (readsize, startpos, partfileName, arquivo, trava) .run (); parts.Add (PartFileName); } latch.await (); // aguardando que todos os arquivos sejam escritos // as linhas podem ser cortadas durante o corte, e todos os arquivos divididos podem ser processados, fusão (partes); devolver peças; } / ** * Processamento de segmento Runnable * * @author supeidong * / classe privada implementos Splitrunnable runnable {int byTesize; String partfilename; Arquivo de origem de arquivo; longo startpos; Countdownlatch Latch; public splitrunnable (int bytesize, longo startpos, string partfilename, arquivo de origem de arquivo, latch de contagemDownlatch) {this.startpos = startpos; this.bytesize = bytesize; this.PartFilename = PartFileName; this.originfile = Originfile; this.latch = latch; } public void run () {RandomAccessFile rfile; OutputStream OS; tente {rfile = new RandomAccessFile (OriginFile, "R"); byte [] b = novo byte [bytesize]; rfile.seek (startpos); // mova o ponteiro para o início de cada "segmento" int s = rfile.read (b); OS = new FileOutputStream (PartFileName); OS.WRITE (B, 0, S); os.flush (); os.close (); latch.CountDown (); } catch (ioexception e) {log.error (e.getMessage ()); latch.CountDown (); }}} / ** * Mesclar linhas de corte * * @param peças * / private void fusão (list <string> partes) {list <sicfile> partesfiles = new ArrayList <StocFile> (); tente {// Assenhe o objeto da tabela dividida para (int i = 0; i <partes.size (); i ++) {string partfileName = partes.get (i); Arquivo splitFilETEMP = novo arquivo (PartFileName); if (splitfiletemp.exists ()) {partfile partfile = new PartFile (); BUBLEREDREADER LEITOR = NEW BUMBERREDRADER (novo InputStreamReader (new FileInputStream (SplitFilETEMP), "GBK")); String firststrow = reader.readline (); String SecondRow = reader.readline (); String endrow = readLastline (partfileName); partfile.setPartFileName (PartFileName); partfile.setFirstrow (Firstrow); partfile.setEndrow (endrow); if (i> = 1) {string prePartFile = Parts.get (i - 1); String preendrow = readLastLine (prepartFile); partfile.setFirstisfull (getCharCount (firstrow+preendrow)> getCharCount (SecondRow)); } Partfiles.add (PartFile); leitor.close (); }} // Escreva as linhas que precisam ser mescladas para (int i = 0; i <partfiles.size () - 1; i ++) {partfile partfile = partfiles.get (i); Partfile partfilenext = partfiles.get (i + 1); Stringbuilder sb = new stringbuilder (); if (partfilenext.getfirstisfull ()) {sb.append ("/r/n"); sb.append (partfilenext.getfirstrow ()); } else {sb.append (partfilenext.getfirstrow ()); } writeLastline (partfile.getPartFileName (), sb.toString ()); }} catch (Exceção e) {log.error (e.getMessage ()); }} / ** * Obtenha o número de vezes que um caractere aparece * @param s * @return * / private int getCharCount (string s) {int count = 0; for (int i = 0; i <s.Length (); i ++) {if (s.charat (i) == cvSseParator) {count ++; }} Retornar contagem; } / ** * Use bufferInputStream para ler o número de linhas de arquivo * * @param filename * @return * / public int getFilerow (string filename) lança ioexception {inputStream is = new bufferInputInputStream (new FileInputStream (fileName)); byte [] c = novo byte [1024]; int conting = 0; int readchars = 0; while ((readchars = is.read (c))! = -1) {for (int i = 0; i <readchars; ++ i) {if (c [i] == '/n') ++ contagem; }} is.close (); contagem de retorno; } / ** * Leia a última linha de dados * @param filename * @return * @throws ioexception * / private string readLastLine (string fileName) lança ioexception {// use RandomAccessFile, encontre a última linha de dados de atrás do RandomAccessFile RAF = RALACESSFILE (FILENAME, "R."; longo len = raf.length (); String lastLine = ""; if (len! = 0l) {longo pos = len - 1; while (pos> 0) {pos--; RAF.SEEK (POS); if (raf.readbyte () == '/n') {lastline = raf.readline (); lastLine = new String (LastLine.GetBytes ("8859_1"), "GBK"); quebrar; }}}} raf.close (); retornar lastline; } / ** * Modifique a última linha de dados * @param filename * @param lastString * @return * @throws ioexception * / private void writeLastline (nome do arquivo de string, string laststring) {try) {// Abra um fluxo de arquivo de acesso aleatório e leitura e de acordo com o método de leitura e write RandomAcssfile "; // Comprimento do arquivo, número de bytes long fileLength = randomfile.length (); // Mova o ponteiro do arquivo de gravação para o final do arquivo. RandomFile.Seek (comprimento do arquivo); // GBK deve ser adicionado aqui, caso contrário, lisou RandomFile.Write (LastString.GetBytes ("GBK")); Randomfile.close (); } catch (ioexception e) {log.error (e.getMessage ()); }} / ** * preenchimento esquerdo * * @param str * @param comprimento * @param ch * @return * / public static string leftpad (string str, int comprimento, char ch) {if (str.Length ()> = length) {return str; } char [] chs = novo char [comprimento]; Arrays.Fill (CHS, CH); char [] src = str.toCharArray (); System.arraycopy (src, 0, chs, comprimento - src.length, src.length); return New String (CHS); } / *** Mesclar linha de arquivo Classe interna* / classe PartFile {private String PartFileName; Firstrow de corda privada; String private Endrow; Privado booleano Firstisfull; public String getPartFileName () {return PartFileName; } public void setPartFilename (String partfileName) {this.partFilename = PartFileName; } public string getfirstrow () {return firststrow; } public void setFirstrow (String firstrow) {this.firstrow = firstrow; } public String getEndRow () {return endrow; } public void setendrow (string endrow) {this.endrow = endrow; } public boolean getfirstisfull () {return Firstisfull; } public void setfirstisfull (boolean firstisfull) {this.firstisfull = Firstisfull; }}}O exposto acima é tudo sobre este artigo, espero que seja útil para todos aprenderem a programação Java.