JAVA——一次性读取或者写入文本文件所有内容

一次性读取文本文件所有内容

public String readFileToString(String fileName) {  
        String encoding = "UTF-8";  
        File file = new File(fileName);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        FileInputStream in=null;
        try {  
            in = new FileInputStream(file);  
            in.read(filecontent);  
            return new String(filecontent, encoding);
        } catch (IOException e) {  
            e.printStackTrace();  
            return null;
        } finally {  
        	try {
				in.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}  
        }  
    }  

一次性写入文本文件所有内容 

public void saveStringTOFile(File file,String content){
		   FileWriter writer=null;
		try {
			writer = new FileWriter(file);
			writer.write(content);
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
	}

参考文章

https://blog.csdn.net/testcs_dn/article/details/41982939

https://www.cnblogs.com/wylblogs/p/readFile.html

发布了1345 篇原创文章 · 获赞 226 · 访问量 28万+

猜你喜欢

转载自blog.csdn.net/weixin_43272781/article/details/103214009