Here you can find the source of readFile(String filePath)
Parameter | Description |
---|---|
filePath | The path of the file to read |
Parameter | Description |
---|---|
IOException | If it failed |
public static String readFile(String filePath) throws IOException
//package com.java2s; /*//from w w w .ja v a2 s.co m * Copyright 2015 TheShark34 * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { /** * Read a file using nio * * @param filePath * The path of the file to read * @return What it read in file (as a string) * @throws IOException * If it failed */ public static String readFile(String filePath) throws IOException { String readString = ""; RandomAccessFile file = new RandomAccessFile(filePath, "r"); FileChannel channel = file.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (channel.read(buffer) > 0) { buffer.flip(); for (int i = 0; i < buffer.limit(); i++) readString += (char) buffer.get(); buffer.clear(); } channel.close(); file.close(); return readString; } }