JAVA读取本地文件中的字符串并赋值到变量

方法挺多的,我选择一种比较简单的方法,其它方法参考该博主博文:https://blog.csdn.net/cunchi4221/article/details/107471069

使用Files类将文件读取为字符串:


 1 package com.example.test;
 2 
 3 
 4 import java.io.IOException;
 5 import java.nio.file.Files;
 6 import java.nio.file.Paths;
 7 
 8 
 9 public class test {
10     public static void main(String[] args){
11         String FileName = "D:\\test.txt";
12         String id = readUsingFiles(FileName);
13         System.out.println("This is ID:\n" + id);
14     }
15     private static String readUsingFiles(String FileName) {
16         try {
17             return new String(Files.readAllBytes(Paths.get(FileName)));
18         } catch (IOException e) {
19             e.printStackTrace();
20             return null;
21         }
22     }
23 }

 

posted @ 2021-09-08 11:25  Kangbaz1  阅读(552)  评论(0编辑  收藏  举报