Este artículo comparte el código específico de la herramienta de lectura y escritura de archivos Java para su referencia. El contenido específico es el siguiente
import java.io.bufferedInputStream; import java.io.bufferedOutputStream; import java.io.bufferedReader; import java.io.file; import java.io.fileInputStream; import java.io.filereader; import java.io.filerarader; java.io.inputstream; import java.io.inputstreamreader; import java.io.outputstream; import java.io.printwriter; import java.net.urlencoder; import java.util.arrayList; import java.util.calendar; import java.util.date; import java.util.util.util. java.util.hashset; import java.util.list; import javax.servlet.http.httpservletResponse;/** * <p> Clase de herramienta de operación de archivo <p> * @version 1.0 * @author li_hao * @date 18 de enero de 2017 */ @supressarnings ({"Resources", "sin inicio"})}) * Obtenga el directorio raíz del proyecto de 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.substring (1, longitud } / *** cadena a la matriz* @param str string* @param Splitstr Delimiter* @return* / public static string [] StringToArray (String Str, String SplitStr) {String [] arraystr = null; if (! "". igual (str) && str! = null) {if (str.indexof (splitStr)! =-1) {arraystr = str.split (splitstr); } else {arraystr = new String [1]; arraystr [0] = str; }} return arraystr; } / ** * Read File * * @param ruta * @return * / public static string readFile (string ruta) {bufferedReader lector = null; Cadena laststr = ""; intente {fileInputStream fileInputStream = new FileInputStream (PATH); InputStreamReader inputStreamReader = new InputStreamReader (fileInputStream, "UTF-8"); lector = new BufferedReader (inputStreamReader); Cadena temptring = null; while ((temptring = lector.readline ())! = null) {laststr += tempstring; } lector.close (); } catch (ioException e) {E.PrintStackTrace (); } Finalmente {if (lector! = null) {try {reader.close (); } catch (ioException e) {E.PrintStackTrace (); }}} return LastStr; } /** * Obtenga los nombres de todos los archivos en la carpeta + consulta Fuzzy (cuando no hay necesidad de consulta difusa, Qerystr se puede pasar vacío o nulo) * 1. Cuando la ruta no existe, el mapa devuelve el valor rettype es 1 * 2. IS 3, Lista de nombre de archivo FileNAmelist, Lista de FolderName FolderNamElist * @param carpoderPath ruta * @param QueryStr Fuzzy Consulty String * @return */ public static Hashmap <String, Object> getFilesName (String FolderPath, String Querystr) {Hashmap <String> Map = Map = New Hashmap <> ();; LIST <String> FileNAmelist = new ArrayList <> (); // Lista de nombres de archivo Lista <String> FolderNamElist = new ArrayList <> (); // Lista de nombres de carpetas F = New File (FolderPath); if (! f.exists ()) {// La ruta no existe map.put ("rettype", "1"); } else {Boolean Flag = F.ISDirectory (); if (flag == false) {// La ruta es archivo map.put ("rettype", "2"); map.put ("nombre de archivo", f.getName ()); } else {// La ruta es carpeta map.put ("rettype", "3"); Archivo fa [] = f.listFiles (); Querystr = Querystr == NULL? "": QueryStr; // Si Qerystr se pasa a NULL, reemplácelo con vacío (índice de valor coincidente no puede ser nulo) para (int i = 0; i <fa.length; i ++) {file 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); }} mapa de retorno; } / ** * Lea el archivo en unidades de comportamiento y lea a la última línea * @param filepath * @return * / public static list <String> readFileContent (string filepath) {bufferedreader lector = null; List <String> listContent = new ArrayList <> (); intente {lector = new BufferedReader (new FileReader (FilePath)); Cadena temptring = null; line int = 1; // Leer una línea a la vez hasta que NULL esté el final del archivo mientras ((temptring = lector.readline ())! = Null) {listContent.Add (temptring); línea ++; } lector.close (); } catch (ioException e) {E.PrintStackTrace (); } Finalmente {if (lector! = null) {try {reader.close (); } catch (ioException e1) {}}} return listContent; } / ** * Lea los datos de la fila especificados, Nota: 0 es la línea de inicio * @param filepath * @param lino * @return * / public static string readlineContent (string filePath, int linEnumber) {bufferedReader lector = null; Cadena lineContent = ""; intente {lector = new BufferedReader (new FileReader (FilePath)); int line = 0; while (line <= Linenumber) {lineContent = Reader.readline (); línea ++; } lector.close (); } catch (ioException e) {E.PrintStackTrace (); } Finalmente {if (lector! = null) {try {reader.close (); } catch (ioException e1) {}} return lineContent; } /** * Read data from beginLine to endLine (including beginLine and endLine), note: 0 is the start line* @param filePath * @param beginLineNumber Start line* @param endLineNumber End line* @return */ public static List<String> readLinesContent(String filePath,int beginLineNumber,int endLineNumber){ List<String> listContent = new ArrayList<>(); intente {int count = 0; BufferedReader lector = new BufferedReader (nuevo FileReader (FilePath)); String Content = Reader.ReadLine (); while (content! = null) {if (count> = beginlineumber && count <= endlineNumber) {listContent.Add (content); } content = Reader.readline (); contar ++; }} capt (excepción e) {} return listContent; } / ** * Lea todos los datos en varios archivos * @param listFilePath * @return * / public static list <String> readFileContent_List (list <string> listFilePath) {list <string> listContent = new ArrayList <> (); for (string filepath: listFilePath) {archivo archivo = nuevo archivo (filePath); BufferedReader lector = null; intente {lector = new BufferedReader (new FileReader (archivo)); Cadena temptring = null; line int = 1; // Leer una línea a la vez hasta que NULL esté el final del archivo mientras ((temptring = lector.readline ())! = Null) {listContent.Add (temptring); línea ++; } lector.close (); } catch (ioException e) {E.PrintStackTrace (); } Finalmente {if (lector! = null) {try {reader.close (); } catch (ioException e1) {}}}} return listContent; } /** * Los datos del archivo están escritos (si las carpetas y los archivos no existen, se crean primero y luego se escriben) * @param filepath * @param content * @param flag VERDADERO: Si el archivo existe y el contenido existe, el contenido se agrega en una nueva línea; falso: si existe el archivo y existe el contenido, el contenido se reemplaza*/ public static string fileLineswrite (string filepath, string content, bandera boolean) {string filedo = "write"; FileWriter fw = null; intente {archivo archivo = nuevo archivo (filepath); // Si la carpeta no existe, cree la carpeta if (! File.getParentFile (). Exists ()) {file.getParentFile (). Mkdirs (); } if (! file.exists ()) {// Si el archivo no existe, cree el archivo y escriba la primera línea de contenido file.createenewfile (); fw = nuevo FileWriter (archivo); archedo = "Crear"; } else {// si el archivo existe, agrega o reemplaza el contenido fw = nuevo FileWriter (archivo, indicador); }} catch (ioException e) {E.PrintStackTrace (); } PrintWriter pw = new PrintWriter (FW); pw.println (contenido); pw.flush (); intente {fw.flush (); pw.close (); fw.close (); } catch (ioException e) {E.PrintStackTrace (); } retorno archedo; } / ** * Escribir archivo * @param ins * @param out * / public static void writeTout (InputStream Ins, OutputStream Out) {byte [] bb = new Byte [10 * 1024]; intente {int cnt = ins.read (bb); while (cnt> 0) {out.write (bb, 0, cnt); cnt = ins.read (bb); }} catch (ioException e) {E.PrintStackTrace (); } finalmente {try {out.flush (); ins.close (); out.close (); } catch (ioException e) {E.PrintStackTrace (); }}} / ** * Determine si los elementos en la lista son exactamente los mismos (return true si exactamente lo mismo, de lo contrario, return false) * @param list * @return * / private static boolean Hassame (list <? Extends Object> list) {if (null == list) return false; return 1 == New Hashset <ject> (list) .size (); } / ** * Determine si hay elementos duplicados en la lista (return true si no duplicado, de lo contrario return false) * @param list * @return * / private static boolean Hassame2 (list <? Extends object> list) {if (null == list) return false; return list.size () == New Hashset <ject> (list) .size (); }/** * aumentar/disminuir el número de días * @param fecha * @param num * @return */public static dateDorSub (fecha de fecha, int num) {calendar startDt = calendar.getInstance (); startdt.settime (fecha); startdt.add (calendar.day_of_month, num); return startdt.gettime (); }}Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.