| 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | package org.chromium.base.test.util; |
| 6 | |
| 7 | import java.io.File; |
| 8 | import java.io.FileInputStream; |
| 9 | import java.io.FileNotFoundException; |
| 10 | import java.io.FileOutputStream; |
| 11 | import java.io.IOException; |
| 12 | import java.io.InputStreamReader; |
| 13 | import java.io.OutputStreamWriter; |
| 14 | import java.io.Reader; |
| 15 | import java.io.Writer; |
| 16 | import java.util.Arrays; |
| 17 | |
| 18 | /** |
| 19 | * Utility class for dealing with files for test. |
| 20 | */ |
| 21 | public class TestFileUtil { |
| 22 | public static void createNewHtmlFile(String name, String title, String body) |
| 23 | throws IOException { |
| 24 | File file = new File(name); |
| 25 | if (!file.createNewFile()) { |
| 26 | throw new IOException("File \"" + name + "\" already exists"); |
| 27 | } |
| 28 | |
| 29 | Writer writer = null; |
| 30 | try { |
| 31 | writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); |
| 32 | writer.write("<html><meta charset=\"UTF-8\" />" + |
| 33 | "<head><title>" + title + "</title></head>" + |
| 34 | "<body>" + |
| 35 | (body != null ? body : "") + |
| 36 | "</body>" + |
| 37 | "</html>"); |
| 38 | } finally { |
| 39 | if (writer != null) { |
| 40 | writer.close(); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | public static void deleteFile(String name) { |
| 46 | File file = new File(name); |
| 47 | file.delete(); |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * @param fileName the file to read in. |
| 52 | * @param sizeLimit cap on the file size: will throw an exception if exceeded |
| 53 | * @return Array of chars read from the file |
| 54 | * @throws FileNotFoundException file does not exceed |
| 55 | * @throws IOException error encountered accessing the file |
| 56 | */ |
| 57 | public static char[] readUtf8File(String fileName, int sizeLimit) throws |
| 58 | FileNotFoundException, IOException { |
| 59 | Reader reader = null; |
| 60 | try { |
| 61 | File f = new File(fileName); |
| 62 | if (f.length() > sizeLimit) { |
| 63 | throw new IOException("File " + fileName + " length " + f.length() + |
| 64 | " exceeds limit " + sizeLimit); |
| 65 | } |
| 66 | char[] buffer = new char[(int) f.length()]; |
| 67 | reader = new InputStreamReader(new FileInputStream(f), "UTF-8"); |
| 68 | int charsRead = reader.read(buffer); |
| 69 | // Debug check that we've exhausted the input stream (will fail e.g. if the |
| 70 | // file grew after we inspected its length). |
| 71 | assert !reader.ready(); |
| 72 | return charsRead < buffer.length ? Arrays.copyOfRange(buffer, 0, charsRead) : buffer; |
| 73 | } finally { |
| 74 | if (reader != null) reader.close(); |
| 75 | } |
| 76 | } |
| 77 | } |