当前位置:网站首页>Classe d'outils commune de fichier, application liée au flux (enregistrement)
Classe d'outils commune de fichier, application liée au flux (enregistrement)
2022-06-29 15:20:00 【Quel arbre】
FileEnregistrement de la méthode commune de classe,IOApplication en continu,(Traitement des fichiers compressés,urlTéléchargement de fichiers)Attendez....
import java.io.File; //Méthodes pratiques.
// createNewFile() throws IOException Créer un nouveau fichier
File file = new File("E:/Nouveaux documents.txt");
// mkdirs() Créer un répertoire à plusieurs niveaux
File file = new File("E:/aa/bb/cc");
File file = new File("E:/Uicode.dat");
boolean file1 = file.isFile();//Oui Non -Documentation
boolean directory = file.isDirectory();// Oui Non -Table des matières
boolean exists = file.exists();//Déterminer si un fichier ou un répertoire existe
boolean b = file.canRead();//Déterminer si le fichier est lisible
boolean b1 = file.canWrite();//Déterminer si le document peut être écrit
boolean hidden = file.isHidden();//Déterminer si le fichier est caché
//Valeur
String absolutePath = file.getAbsolutePath();//Obtenir le chemin absolu
String path = file.getPath();//Obtenir le chemin relatif
String name = file.getName();//Obtenir le nom du fichier ou du Répertoire
long length = file.length();//Obtenir la taille du fichier
long l = file.lastModified();//Obtenir la dernière modification du fichier,Milliseconde TIMESTAMP.
String parent = file.getParent();// Obtenir le nom du dossier dans lequel
System.out.println("Chemin absolu"+absolutePath);
System.out.println("Chemin relatif"+path);
System.out.println(" Nom du Répertoire de fichiers "+name);
System.out.println("Taille du fichier"+length);
System.out.println("Dernière modification"+ new Date(l));
System.out.println(" Obtenir le nom du dossier dans lequel "+parent);
IO Flow .Flux d'octets: Le flux le plus primitif , Les données lues sont 010101 Cette représentation minimale des données , C'est juste qu'il est lu en octets ,Un octet(byte)- Oui.8(bit), Lire est un octet à lire mot par mot .
Flux de caractères: Lire les données un par un .1Les caractères2Octets
Dites entrées - sorties ,Tous. Pour le programme !!
Flux nodal: Peut être obtenu à partir d'une source de données spécifique (Noeud)Lire et écrire des données.( Un tuyau )
Flux de traitement: Est au - dessus d'un flux existant ,Fournir aux programmes des capacités de lecture et d'écriture plus puissantes grâce au traitement des données.( Le tuyau est enveloppé dans le tuyau )

//Flux d'entrée
InputStream
//Méthodes courantes Retour -1 Fin du flux d'entrée
int read() throws IOException
String readLine();//Lire ligne par ligne
synchronized void mark(int var1)//Marquer
synchronized void reset()// Retour à la marque
// Désactiver le flux pour libérer les ressources de mémoire
void close()
//Flux de sortie
OutputStream
void write(int b) throws IOException
void newLine();//Nouvelle ligne
void flush() throws IOException
void close() throws IOException
//Exemple
while ((b=in.read())!= -1){
out.write(b);
}
Classe utilitaire
/** * Compression des fichiers. Compression par défaut dans le répertoire frère (Chiffrement non pris en charge) * @param sourceFileName Fichier source,eg:E:/text.txt * @param format Format de compression rar zip * @return result * @throws Exception */
public static Result compressFile(String sourceFileName,String format) throws Exception {
String fileSuffix;Suffixe de fichier eg: .txt
String zipName;//Nom du fichier compressé
File file = new File(sourceFileName);
if (sourceFileName.lastIndexOf(".") != -1){
//Est un répertoire
fileSuffix = sourceFileName.substring(sourceFileName.lastIndexOf("."));//Suffixe
zipName=sourceFileName.replaceAll(fileSuffix,"")+"."+format;
}else {
zipName=file.getParent()+File.separator+sourceFileName.substring(sourceFileName.lastIndexOf("/")).replaceAll("/","")+"."+format;
}
long startTime=System.currentTimeMillis();
//CréationzipFlux de sortie
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipName));
File sourceFile = new File(sourceFileName);
//Appelez la fonction
compress(out, sourceFile, sourceFile.getName());// sourceFile.getName() E:/aa/bb namePour aa.
out.close();
long endTime=System.currentTimeMillis();
logger.info("Compression terminée!"+",Ça prend du temps:"+(endTime-startTime)+"MS");
logger.info("Chemin de sortie:"+zipName);
return Result.ok("Compression terminée"+",Ça prend du temps:"+(endTime-startTime)+"MS");
}
public static void compress(ZipOutputStream out, File sourceFile, String base) throws Exception {
//Si le chemin est un répertoire(Dossiers)
if(sourceFile.isDirectory()) {
//Extraire les fichiers du dossier(Ou sous - dossiers)
File[] flist = sourceFile.listFiles();
if(flist.length==0) {
//Si le dossier est vide,Juste à destinationzip Écrivez un point d'entrée de répertoire dans le fichier
System.out.println(base + File.separator);
out.putNextEntry(new ZipEntry(base + File.separator));
} else {
//Si le dossier n'est pas vide,Appelé Récursivementcompress,Chaque fichier dans le dossier(Ou dossier)Pour compresser
for(int i=0; i<flist.length; i++) {
compress(out, flist[i], base+File.separator+flist[i].getName());
}
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int len;
byte[] buf = new byte[1024];
System.out.println(base);
while((len=bis.read(buf, 0, 1024)) != -1) {
out.write(buf, 0, len);
}
bis.close();
fos.close();
}
}
/** * Version Hao ge * Décompression du paquet de compression, Décryptage non pris en charge ,Soutienrar,zip Format * @param srcFile Fichier source * @param destDirPath Répertoire de sortie */
public static Result uncompressFile(File srcFile,String destDirPath){
long start = System.currentTimeMillis();
// Déterminer si le fichier source existe
if (!srcFile.exists()) {
return Result.error(srcFile.getPath() + "Le fichier source n'existe pas");
}
// Commencez à décompresser
ZipFile zipFile = null;
try {
zipFile = new ZipFile(srcFile);
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("Décompresser" + entry.getName());
// Si c'est un dossier,Créer des dossiers
if (entry.isDirectory()) {
String dirPath = destDirPath + "/" + entry.getName();
File dir = new File(dirPath);
dir.mkdirs();
} else {
// Si c'est un document,Créez d'abord un fichier,Et utiliserioContenu du fluxcopyLe passé.
File targetFile = new File(destDirPath + "/" + entry.getName());
// Assurez - vous que le dossier parent de ce fichier doit exister
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// Écrire le contenu du fichier compressé dans ce fichier
InputStream is = zipFile.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// Séquence de fermeture,Ouvert puis fermé
fos.close();
is.close();
}
}
long end = System.currentTimeMillis();
logger.info("Décompression terminée,Ça prend du temps:" + (end - start) +"MS");
return Result.ok("Décompression terminée,Ça prend du temps:" + (end - start) +"MS");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(zipFile != null){
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Result.error("Échec de la décompression");
}
/** * Décompresser .gzFormat,Compresser le fichier * @param inFileName eg: E:\\2019072308.gz */
public static void uncompressGz(String inFileName) {
try {
if (!getExtension(inFileName).equalsIgnoreCase("gz")) {
System.err.println(" Le fichier n'est pasgzType Pack ");
System.exit(1);
}
System.out.println("Commencer à Décompresser le fichier....");
Long startTime=System.currentTimeMillis();
GZIPInputStream in = null;
try {
in = new GZIPInputStream(new FileInputStream(inFileName));
} catch(FileNotFoundException e) {
System.err.println("File not found. " + inFileName);
System.exit(1);
}
System.out.println("Open the output file.");
String outFileName = getFileName(inFileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(outFileName);
} catch (FileNotFoundException e) {
System.err.println("Could not write to file. " + outFileName);
System.exit(1);
}
System.out.println("Transfering bytes from compressed file to the output file.");
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
Long endTime=System.currentTimeMillis();
System.out.println("Décompression terminée,Ça prend du temps:"+(startTime-endTime)+"MS");
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
/** * Obtenir une extension de fichier * @param f E:\\2019072308.gz * @return <code>String</code> representing the extension of the incoming * file. */
public static String getExtension(String f) {
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
ext = f.substring(i+1);
}
return ext;
}
/** * Pour extraire un nom de fichier sans extension * @param f Incoming file to get the filename * @return <code>String</code> representing the filename without its * extension. */
public static String getFileName(String f) {
String fname = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
fname = f.substring(0,i);
}
return fname;
}
/** * Lire les données du fichier dans l'unit é de comportement . * UtiliserBufferedReaderLire le fichier en unités de comportement, Lire la dernière ligne . * @param is DocumentationIOFlow * @param c Cache UtiliserBufferedReader, Par défaut, chaque lecture (5 * 1024 * 1024)5MDonnées.DiminutionIO * @return List<String> */
public static List<String> readFileContent(InputStream is, int c) {
BufferedReader reader = null;
List<String> listContent = new ArrayList<>();
try {
BufferedInputStream bis = new BufferedInputStream(is);
reader = new BufferedReader(new InputStreamReader(bis, "utf-8"), c==0?5 * 1024 * 1024:c);//Cache
String tempString = null;
// Lire une ligne à la fois,Jusqu'à ce qu'il soit lunullFin du fichier
while ((tempString = reader.readLine()) != null) {
listContent.add(tempString);
}
is.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return listContent;
}
/** * Écrire du contenu au fichier en unités de comportement * @param contest Collection de contenu * @param os new FileOutputStream(filePath) * @param c c Cache UtiliserBufferedReader, Par défaut, chaque lecture (5 * 1024 * 1024)5MDonnées.DiminutionIO */
public static void writeFileContent(List<String> contest,OutputStream os,int c){
BufferedWriter bw;
try {
BufferedOutputStream bos = new BufferedOutputStream(os);
bw = new BufferedWriter(new OutputStreamWriter(bos, StandardCharsets.UTF_8), c==0?5 * 1024 * 1024:c);
for(String str:contest){
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
}catch (IOException e){
e.printStackTrace();
}
}
/** * Du réseauUrlTéléchargement de fichiers dans * @param urlStr * @param fileName * @param savePath * @throws IOException */
public static void downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//Réglez le délai à3Secondes
conn.setConnectTimeout(3*1000);
//Empêcher le programme de masquage de saisir et de retourner403Erreur
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//Obtenir le flux d'entrée
InputStream inputStream = conn.getInputStream();
// Obtenez votre propre Tableau
byte[] getData = readInputStream(inputStream);
//Emplacement de l'enregistrement du fichier
File saveDir = new File(savePath);
if(!saveDir.exists()){
saveDir.mkdir();
}
File file = new File(saveDir+ File.separator+fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
System.out.println("info:"+url+" download success");
}
/** * Obtenir un tableau d'octets à partir du flux d'entrée * @param inputStream * @return * @throws IOException */
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/** * Téléchargement de fichiers , Fenêtre de téléchargement pop - up du navigateur ,Type * @param response response * @param AbsolutePath Chemin absolu,Chemin complet eg:E://a.text ; * @param FileName Nom du fichier eg: a.text; */
public static void downLoadFile(HttpServletResponse response, HttpServletRequest request, String AbsolutePath, String FileName) throws Exception{
// Obtenir par nom de fichier MIMEType
String contentType = request.getServletContext().getMimeType(FileName);
String contentDisposition = "attachment;filename=" + filenameEncoding(FileName, request);
// Flux de fichiers
FileInputStream input = new FileInputStream(AbsolutePath);
//Définir la tête
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", contentDisposition);
// Obtenir un flux lié au côté de la réponse
ServletOutputStream output = response.getOutputStream();
//Écrire les données du flux d'entrée au flux de sortie.--- Le noeud du flux de sortie est le client
IOUtils.copy(input, output);
input.close();
}
/** * Télécharger le Code du fichier * @param filename Nom du fichier * @param request request * @throws IOException */
public static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
String agent = request.getHeader("User-Agent"); //Obtenir le navigateur
if (agent.contains("Firefox")) {
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?"+ base64Encoder.encode(filename.getBytes("utf-8"))+ "?=";
} else if(agent.contains("MSIE")) {
filename = URLEncoder.encode(filename, "utf-8");
} else {
filename = URLEncoder.encode(filename, "utf-8");
}
return filename;
}
Application:Scénario d'affaires, AppelezAPI,RetourJSONMoyenne, Lien de téléchargement avec chat , Lors du téléchargement du fichier .gzPaquet compressé
–.Décompresser,Lire le document,TraitementJSONDonnées,Tourne.list
public static void main(String[] args) throws Exception{
try{
//Télécharger,Paquet compressé
FileUtil.downLoadFromUrl("http://ebs-chatmessage-a1.easemob.com/history/3D/1111170113115695/xianglekang/2019072613.gz?Expires=1564124524&OSSAccessKeyId=LTAIlKPZStPokdA8&Signature=1fYR1i3pf%2FpRfJPqR882wIEwuWk%3D",
"2019072613.gz","E:/");
}catch (Exception e) {
e.printStackTrace();
}
//Décompresser
FileUtil.uncompressGz("E:\\2019072613.gz");
List<String> list = FileUtil.readFileContent(new FileInputStream("E:/2019072613"), 5);
List<HxMsg> msgList= new ArrayList<>();
HxMsg hxMsg = new HxMsg();
for (String s:list ) {
JSONObject jsonObject=JSONObject.parseObject(s);
hxMsg.setChatType(jsonObject.getString("chat_type"));
hxMsg.setMsg(JSONObject.parseArray(jsonObject.getJSONObject("payload").getString("bodies")).getJSONObject(0).getString("msg"));
hxMsg.setType(JSONObject.parseArray(jsonObject.getJSONObject("payload").getString("bodies")).getJSONObject(0).getString("type"));
hxMsg.setFrom(jsonObject.getString("from"));
hxMsg.setTo(jsonObject.getString("to"));
hxMsg.setTimesTamp(jsonObject.getString("timestamp"));
msgList.add(hxMsg);
hxMsg = new HxMsg();
}
System.out.println(msgList.toString());
}
边栏推荐
- Unity C# 基础复习28——带返回的委托(P449)
- Review of digital image processing
- 雷达天线简介
- 从雷达回波中可获取的信息
- Secondary pointer
- MCS:多元随机变量——多项式分布
- 广州期货正规吗?如果有人喊你用自己的手机登,帮忙开户,安全吗?
- MCS:离散随机变量——Pascal分布
- message from server: “Host ‘xxxxxx‘ is blocked because of many connection errors; unblock with ‘m
- Get the width of text component content
猜你喜欢
随机推荐
信息学奥赛一本通1001:Hello,World!
Const usage
BioVendor游离轻链(κ和λ)Elisa 试剂盒的化学性质
极化SAR几种成像模式
Lumiprobe 活性染料丨氨基染料:花青5胺
.NET程序配置文件操作(ini,cfg,config)
雷达发射机
Northwestern Polytechnic University attacked by overseas e-mail
LeetCode笔记:Weekly Contest 299
Solution to the problem that the assembly drawing cannot be recognized after the storage position of SolidWorks part drawing is changed
Abnormal logic reasoning problem of Huawei software test written test [2] Huawei hot interview problem
konva系列教程4:图形属性
bash汇总线上日志
Differential equations of satellite motion
在shop工程中,实现一个菜单(增删改查)
信息学奥赛一本通2061:梯形面积
PostgreSQL learning (based on rookie course)
关于SQL+NoSQL : NewSQL数据库
Wechat official account - menu
我 35 岁,可以转行当程序员吗?








