Este artigo compartilha o código específico da ferramenta de leitura e escrita de arquivos Java para sua referência. O conteúdo específico é o seguinte
importar java.io.bufferEnputStream; importar java.io.bufferedOutputStream; importar java.io.bufferedReader; importar java.io.file; importar java.io.fileInputStream; importio java.io.fileraderer; importfilexensport; importerano; java.io.inputStream; importar java.io.inputStreamReader; importar java.io.OutputStream; importar java.io.printwriter; importar java.net.urlencoder; importar java.util.arraylist; import.util.Calendar; importar; java.util.HashSet;import java.util.List;import javax.servlet.http.HttpServletResponse;/** * <p>File operation tool class<p> * @version 1.0 * @author li_hao * @date January 18, 2017 */@SuppressWarnings({"resource","unused"})public class FileUtils { /** * Obtenha o diretório raiz do projeto do Windows/ Linux * @return */ public static string getContextPath () {string fileurl = thread.currentThread (). GetContextClassloader (). GetResource (""). GetPath (); if ("usr" .equals (fileurl.substring (1,4))) {fileurl = (fileurl.substring (0, fileurl.length ()-16)); // linux} else {fileurl = (fileurl.subring (1, fileurl.lngength ()-16); } / *** String para Array* @param str string* @param splitstr delimiter* @return* / public static string [] stringtoarray (string str, string splitstr) {string [] Arraystr = null; if (! "". Equals (str) && str! = null) {if (str.indexOf (splitStr)! =-1) {Arraysttr = str.split (splitStr); } else {Arraystr = new String [1]; Arraystr [0] = str; }} retornar Arraystr; } / ** * Leia o arquivo * * @param caminho * @return * / public static string readfile (string path) {buffarredreader leitor = null; String laststr = ""; tente {fileInputStream fileInputStream = new FileInputStream (caminho); InputStreamReader inputStreamReader = new InputStreamReader (FileInputStream, "UTF-8"); leitor = new bufferredreader (inputStreamReader); String tempstring = null; while ((tempstring = leitor.readline ())! = null) {laststr += tempstring; } leitor.close (); } catch (ioexception e) {e.printStackTrace (); } finalmente {if (leitor! = null) {try {reader.close (); } catch (ioexception e) {e.printStackTrace (); }}} retornar LastStr; } /** * Obtenha os nomes de todos os arquivos na pasta + consulta difusa (quando não há necessidade de consulta difusa, o quererystr pode ser passado vazio ou nulo) * 1. Quando o caminho não existe, o mapa retorna o valor do RettyPE, o valor de 1 * 2 * 2. O valor do Rettype é 3, lista de arquivo FILENAMELISTA, LISTA DO FOLDERNAME LIST DRESTERNAMELIST * @PARAM FOLDERPATH PATH * @Param Querystr Fuzzy Query String * @return */ public static hashMap <string, object> getFilesName (String pasherpath, stringfst) {hashmap <String, object> List <String> filenamelist = new ArrayList <> (); // Lista de nomes do arquivo <Stram) FOLDERNAMELIST = new ArrayList <> (); // Nome da pasta Arquivo F = novo arquivo (FolderPath); if (! f.exists ()) {// O caminho não existe map.put ("rettype", "1"); } else {bandeira booleana = f.isdirectory (); if (flag == false) {// o caminho é o arquivo map.put ("rettype", "2"); map.put ("nome do arquivo", f.getName ()); } else {// o caminho é o map.put.put ("Rettype", "3"); Arquivo fa [] = f.listfiles (); Querystr = Querystr == NULL? "": Querystr; // Se o Querystr for passado para NULL, substitua -o por vazio (o valor de correspondência indexOf não pode ser nulo) para (int i = 0; i <fa.length; i ++) {arquivo fs = fa [i]; if (fs.getName (). Indexof (Querystr)! =-1) {if (fs.isDirectory ()) {FolderNameList.add (fs.getName ()); } else {filenamelist.add (fs.getName ()); }}} map.put ("FILENAMELIST", FILENAMELIST); map.put ("FolderNameList", Foldernamelist); }} retornar mapa; } / ** * Leia o arquivo em unidades de comportamento e leia na última linha * @param filepath * @return * / list public static <string> readFileContent (string filepath) {bufferreader leitor = null; List <String> listContent = new ArrayList <> (); tente {reader = new BufferredReader (new FileReader (filepath)); String tempstring = null; int line = 1; // Leia uma linha de cada vez até NULL ser o final do arquivo while ((tempstring = reader.readline ())! = Null) {listContent.add (tempstring); linha ++; } leitor.close (); } catch (ioexception e) {e.printStackTrace (); } finalmente {if (leitor! = null) {try {reader.close (); } catch (ioexception e1) {}}} retorna listContent; } / ** * Leia os dados da linha especificada, Nota: 0 é a linha de partida * @param filepath * @param linenumber * @return * / public static string readlineContent (string filepath, int linenumber) {buffarredreader leitor = null; String linecontent = ""; tente {reader = new BufferredReader (new FileReader (filepath)); int line = 0; while (linha <= linenumber) {linecontent = leitor.readline (); linha ++; } leitor.close (); } catch (ioexception e) {e.printStackTrace (); } finalmente {if (leitor! = null) {try {reader.close (); } catch (ioexception e1) {}} retorna linecontent; } / *** Leia os dados de BeginLine para Endline (incluindo linha iniciante e EndLine), Nota: 0 é a linha de partida* @param filepath* @param BEGNLINENNumber Linha de partida* @param endlineNumber Linha final* @RETURN* / public static list <tring> ReadLinesContent (string filepath, Int BeginLinEnMumMumber, Int EndLinumMe. tente {int count = 0; Leitor buffarreder leitor = new buffarreder (new filereader (filepath)); String content = reader.readline (); while (content! = null) {if (count> = BeginLinNumber && count <= endlinenNumber) {listContent.add (content); } content = leitor.readline (); contagem ++; }} catch (Exceção e) {} retorna listContent; } / ** * Leia todos os dados em vários arquivos * @param listFilePath * @return * / public static list <tring> readFileContent_list (list <string> listFilePath) {list <tring> listContent = new ArrayList <> (); para (string filepath: listfilepath) {arquivo file = new arquivo (filepath); Leitor buffarreder leitor = null; tente {reader = new BufferredReader (new FileReader (arquivo)); String tempstring = null; int line = 1; // Leia uma linha de cada vez até NULL ser o final do arquivo while ((tempstring = reader.readline ())! = Null) {listContent.add (tempstring); linha ++; } leitor.close (); } catch (ioexception e) {e.printStackTrace (); } finalmente {if (leitor! = null) {try {reader.close (); } catch (ioexception e1) {}}}} retorna listContent; } /** * Os dados do arquivo são gravados (se as pastas e arquivos não existirem, eles serão criados primeiro e depois escritos) * @param filepath * @param Content * @param sinalizador true: Se o arquivo existir e o conteúdo existir, o conteúdo será adicionado em uma nova linha; FALSO: Se existir o arquivo e o conteúdo, o conteúdo será substituído*/ public static string filelineswrite (string filepath, conteúdo da string, sinalizador booleano) {string filedo = "write"; FileWriter fw = null; tente {arquivo file = novo arquivo (filepath); // Se a pasta não existir, crie a pasta if (! File.getParentFile (). Exist ()) {file.getParentFile (). Mkdirs (); } if (! file.exists ()) {// Se o arquivo não existir, crie o arquivo e escreva a primeira linha de conteúdo file.createNewfile (); fw = new FileWriter (arquivo); Filedo = "Criar"; } else {// Se o arquivo existir, anexar ou substituir o conteúdo fw = new FileWriter (arquivo, sinalizador); }} catch (ioexception e) {e.printStackTrace (); } PrintWriter pw = new PrintWriter (FW); pw.println (conteúdo); pw.flush (); tente {fw.flush (); pw.close (); fw.close (); } catch (ioexception e) {e.printStackTrace (); } return arquivado; } / ** * Arquivo de gravação * @param ins * @param out * / public static void writeIntOout (inputStream ins, outputStream out) {byte [] bb = novo byte [10 * 1024]; tente {int cnt = ins.read (bb); while (cnt> 0) {out.write (bb, 0, cnt); cnt = ins.read (bb); }} catch (ioexception e) {e.printStackTrace (); } finalmente {tente {out.flush (); ins.close (); out.Close (); } catch (ioexception e) {e.printStackTrace (); }}} / ** * Determine se os elementos da lista são exatamente os mesmos (retorne verdadeiro se exatamente o mesmo, caso contrário, retorne false) * @param list * @return * / private estático booleano Hassame (list <? Extends Object> list) {if (null == List) retornar false; retornar 1 == novo hashset <ject> (list) .size (); } / ** * Determine se existem elementos duplicados na lista (retorne true se não hound duplicate, caso contrário, retorne false) * @param list * @return * / private estático boolean hassame2 (list <? Extends object> list) {if (null == list) retorna false; return list.size () == novo hashset <ject> (list) .size (); }/** * Aumente/diminua o número de dias * @param data * @param num * @return */public static date dateAdDorSub (data de data, int num) {calendar startDt = calendar.getInstance (); startdt.setTime (data); startdt.add (calendar.day_of_month, num); return startdt.gettime (); }}O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.