集册 Java实例教程 将文件读取到字符串

将文件读取到字符串

欢马劈雪     最近更新时间:2020-01-02 10:19:05

522
读取文件到字符串


//package com.nowjava;

import java.io.*;// from nowjava.com - 时代Java

import java.nio.charset.Charset;


public class Main {

    public static void main(String[] argv) throws Exception {

        String fileName = "nowjava.com";

        System.out.println(fileToString(fileName));

    }


    public static String fileToString(String fileName) {

        File file = new File(fileName);

        InputStream in = null;

        try {

            in = new FileInputStream(file);

        } catch (FileNotFoundException fnfe) {// 来自 时 代 J a v a 公 众 号 - nowjava.com

            System.out.println("File not found: " + fileName);

        }

        byte[] b = new byte[(int) file.length()];

        int len = b.length;

        int total = 0;

        int result = 0;

        while (total < len) {

            try {

                result = in.read(b, total, len - total);

            } catch (IOException ioe) {

                System.out.println("Unable to read from file");

           
展开阅读全文