FileReadUtils.java 17.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
package com.gimi.common.cinema.utils;

import android.text.TextUtils;
import android.util.Log;
import com.gimi.common.cinema.model.CinemaConfig;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import static com.nostra13.universalimageloader.core.download.BaseImageDownloader.XOR_CONST;

/**
 * Created by pc on 2014/12/23.
 */
public class FileReadUtils {

    /**
     * 以字符为单位读取文件,常用于读文本,数字等类型的文件
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字节:");
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。
                // 但如果这两个字符分开显示时,会换两次行。
                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                if (((char) tempchar) != '\r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字节:");
            // 一次读多个字符
            char[] tempchars = new char[30];
            int charread = 0;
            reader = new InputStreamReader(new FileInputStream(fileName));
            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != -1) {
                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != '\r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }

        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static ArrayList<String> readFileByLines(String fileName) {
        ArrayList<String> result = new ArrayList<String>();
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容,一次读一整行:");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                result.add(tempString.trim());
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return result;
    }

    public static ArrayList<String> readLines(String fileName) {
        ArrayList<String> lines = new ArrayList<String>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                lines.add(line);
                System.out.println(line);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    public static String readDoubanId(String fileName, String name) {
        return readString(fileName, name, "#");
    }

    public static int readVersionCode(String fileName, String name) {
        String s = readString(fileName, name, "@");
        int result = 0;
        try {
            result = Integer.parseInt(s.split("@")[1]);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static CinemaConfig readConfigBySamba(String fileName) {
        CinemaConfig cinemaConfig = new CinemaConfig();
        if (!SambaFileCharge.fileExist(fileName)) {
            return cinemaConfig;
        }
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return cinemaConfig;
            }
        }
        String versions = FileReadUtils.readDate(fileName);
        if (!TextUtils.isEmpty(versions)) {
            try {
                cinemaConfig = new Gson().fromJson(versions, new TypeToken<CinemaConfig>() {
                }.getType());
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        } else {
            cinemaConfig.setDbVersion(-1);
            cinemaConfig.setClassVersion(0);
        }
        return cinemaConfig;
    }

    private static String readString(String fileName, String name, String divide) {
        String lines;
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains(name)) {
                    if (!TextUtils.isEmpty(line)) {
                        String[] split = line.split(divide);
                        if (split.length >= 2) {
                            if (split[0].equals(name)) {
                                lines = line;
                                return lines;
                            }
                        }
                    }
                }
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 随机读取文件内容
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容:");
            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                }
            }
        }
    }


    public static String readDate1(String url) {
        try {
            FileReader read = new FileReader(new File(url));
            StringBuffer sb = new StringBuffer();
            char ch[] = new char[1024];
            int d = read.read(ch);
            while (d != -1) {
                String str = new String(ch, 0, d);
                sb.append(str);
                d = read.read(ch);
            }
            read.close();
            return sb.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int readCount(String url) {
        int count = 0;
        try {
            FileReader read = new FileReader(new File(url));
            StringBuffer sb = new StringBuffer();
            char ch[] = new char[1024];
            int d = read.read(ch);
            while (d != -1) {
                String str = new String(ch, 0, d);
                sb.append(str);
                d = read.read(ch);
            }
            read.close();
            String trim = sb.toString().trim();
//            if (TextUtils.isEmpty(trim)) {
//                return 0;
//            }
            String regex = "^(-?[1-9]\\d*\\.?\\d*)|(-?0\\.\\d*[1-9])|(-?[0])|(-?[0]\\.\\d*)$";
            if (trim.matches(regex)) {
                count = Integer.parseInt(trim);//转化失败则返回0
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return count;
        }
        return count;
    }

    public static String readDate(String url) {
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        if (!url.endsWith("qnt")) {
            return readDate1(url);
        }
        StringBuffer sb = new StringBuffer();
        try {
            String encoding = "utf-8";
            File file = new File(url);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                FileInputStream in = new FileInputStream(file);
                InputStream inputStream = getInputStream(in, MM_ENCRYPT_STEP);
                assert inputStream != null;
                InputStreamReader read = new InputStreamReader(inputStream, encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    sb.append(lineTxt);
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static InputStream getInputStream(InputStream fis, int step) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream inputStream = null;
        try {
            int read;
            int bytesWritten = 0;
            byte[] buffer = new byte[step];
            while ((read = fis.read(buffer)) > -1) {
                byte[] otherBuffer = new byte[read - 1];
                baos.write(buffer[0] ^ XOR_CONST);
//                System.arraycopy(buffer, 1, otherBuffer, 0, read - 1);
                for (int i = 1; i < read; i++) {
                    otherBuffer[i - 1] = buffer[i];
                }
                baos.write(otherBuffer, bytesWritten, read - 1);
            }
            byte[] byteArray = baos.toByteArray();
            inputStream = new ByteArrayInputStream(byteArray);
            return inputStream;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 附加写入数据
     */
    public static void writeDate(String path, String content) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
            output.write(content);
            output.close();
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public static final int MM_ENCRYPT_STEP = 40;
    public static final int PICTURE_ENCRYPT_STEP = 4 * 1024;

    /**
     * 附加写入数据
     */
    public static void writeDateByEn(String path, String content) {
        FileOutputStream fop = null;
        int step = MM_ENCRYPT_STEP;
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            fop = new FileOutputStream(file);
            byte[] contentInBytes = content.getBytes();
            encrypt(fop, step, contentInBytes);
            fop.flush();
            fop.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fop != null) {
                    fop.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 附加写入数据
     */
    public static void writeDateByEncrypt(String path, String content) throws IOException {
        FileOutputStream fop;
        int step = MM_ENCRYPT_STEP;
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        fop = new FileOutputStream(file);
        byte[] contentInBytes = content.getBytes();
        encrypt(fop, step, contentInBytes);
        fop.flush();
        fop.close();
        System.out.println("Done");
        fop.close();
    }

    private static void encrypt(FileOutputStream fop, int step, byte[] contentInBytes) throws IOException {
        int cur = 0;
        int read;
        byte[] buffer = new byte[step];
        int length = contentInBytes.length;
        read = length > step ? step : length;
//        System.arraycopy(contentInBytes, cur, buffer, 0, read);
        for (int i = 0; i < read; i++) {
            buffer[i] = contentInBytes[cur + i];
        }
        while (cur < length) {
            fop.write(buffer[0] ^ XOR_CONST);
            byte[] optTypeBuffer = new byte[read - 1];
//            System.arraycopy(buffer, 1, optTypeBuffer, 0, read - 1);
            for (int i = 1; i < read; i++) {
                optTypeBuffer[i - 1] = buffer[i];
            }
            fop.write(optTypeBuffer, 0, read - 1);
            cur += read;
            read = length - cur > step ? step : length - cur;
//            System.arraycopy(contentInBytes, cur, buffer, 0, read);
            for (int i = 0; i < read; i++) {
                buffer[i] = contentInBytes[cur + i];
            }
        }
    }

    /**
     * 附加写入数据
     *
     * @param path
     * @param content
     * @param isAppend 附加还是重写
     */
    public static void writeDates(String path, String content, boolean isAppend) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.createNewFile();
            }
            BufferedWriter output = new BufferedWriter(new FileWriter(file, isAppend));
            output.write(content);
            output.close();
            Log.d("lovely", "╔════════════════════════════════════════════");
            Log.d("lovely", "╟write success ");
            Log.d("lovely", "╚════════════════════════════════════════════");
        } catch (Exception ex) {
            System.out.println(ex);
            Log.d("lovely", "╔════════════════════════════════════════════");
            Log.d("lovely", "╟write failure ");
            Log.d("lovely", "╚════════════════════════════════════════════");
        }
    }

    /**
     * 写入数据
     */
    public static boolean writeDate1(String path, String content) {

        boolean b = false;
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            BufferedWriter output = new BufferedWriter(new FileWriter(file));
            output.write(content);
            output.close();
            b = true;
        } catch (Exception ex) {
            System.out.println(ex);
            b = false;
        }
        return b;
    }
}