1// Copyright 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 5package org.chromium.base.test.util; 6 7import java.io.File; 8import java.io.FileInputStream; 9import java.io.FileNotFoundException; 10import java.io.FileOutputStream; 11import java.io.IOException; 12import java.io.InputStreamReader; 13import java.io.OutputStreamWriter; 14import java.io.Reader; 15import java.io.Writer; 16import java.util.Arrays; 17 18/** 19 * Utility class for dealing with files for test. 20 */ 21public 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 boolean deleted = file.delete(); 48 assert (deleted || !file.exists()); 49 } 50 51 /** 52 * @param fileName the file to read in. 53 * @param sizeLimit cap on the file size: will throw an exception if exceeded 54 * @return Array of chars read from the file 55 * @throws FileNotFoundException file does not exceed 56 * @throws IOException error encountered accessing the file 57 */ 58 public static char[] readUtf8File(String fileName, int sizeLimit) throws 59 FileNotFoundException, IOException { 60 Reader reader = null; 61 try { 62 File f = new File(fileName); 63 if (f.length() > sizeLimit) { 64 throw new IOException("File " + fileName + " length " + f.length() + 65 " exceeds limit " + sizeLimit); 66 } 67 char[] buffer = new char[(int) f.length()]; 68 reader = new InputStreamReader(new FileInputStream(f), "UTF-8"); 69 int charsRead = reader.read(buffer); 70 // Debug check that we've exhausted the input stream (will fail e.g. if the 71 // file grew after we inspected its length). 72 assert !reader.ready(); 73 return charsRead < buffer.length ? Arrays.copyOfRange(buffer, 0, charsRead) : buffer; 74 } finally { 75 if (reader != null) reader.close(); 76 } 77 } 78} 79