Here you can find the source of readFileAsString(String filePath)
Parameter | Description |
---|---|
filePath | The path of the file |
Parameter | Description |
---|---|
IOException | an exception |
public static String readFileAsString(String filePath) throws IOException
//package com.java2s; /**/* w w w .j av a 2 s. com*/ * Copyright (c) 2009 University of Rochester * * This program is free software; you can redistribute it and/or modify it under the terms of the MIT/X11 license. The text of the * license can be found at http://www.opensource.org/licenses/mit-license.php and copy of the license can be found on the project * website http://www.extensiblecatalog.org/. * */ import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { private static final int BUFFER_SIZE = 1024; /** * Read a file content to a string variable * @param filePath The path of the file * @return The file's content * @throws IOException */ public static String readFileAsString(File filePath) throws IOException { return readFileAsString(filePath.getAbsolutePath()); } /** * Read a file content to a string variable * @param filePath The path of the file * @return The file's content * @throws IOException */ public static String readFileAsString(String filePath) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = new BufferedInputStream(new FileInputStream(filePath)); byte[] buf = new byte[BUFFER_SIZE]; int numOfBytes = is.read(buf); while (numOfBytes != -1) { baos.write(buf, 0, numOfBytes); numOfBytes = is.read(buf); } is.close(); return new String(baos.toByteArray(), "UTF-8"); } }