Whole text file to a String in Java

后端 未结 10 2222
遇见更好的自我
遇见更好的自我 2020-12-01 15:44

Does Java has a one line instruction to read to a text file, like what C# has?

I mean, is there something equivalent to this in Java?:

String data =          


        
相关标签:
10条回答
  • 2020-12-01 16:01

    No external libraries needed. The content of the file will be buffered before converting to string.

    Path path = FileSystems.getDefault().getPath(directory, filename);
    String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2020-12-01 16:02

    Not within the main Java libraries, but you can use Guava:

    String data = Files.asCharSource(new File("path.txt"), Charsets.UTF_8).read();
    

    Or to read lines:

    List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );
    

    Of course I'm sure there are other 3rd party libraries which would make it similarly easy - I'm just most familiar with Guava.

    0 讨论(0)
  • 2020-12-01 16:04

    No external libraries needed. The content of the file will be buffered before converting to string.

      String fileContent="";
      try {
              File f = new File("path2file");
              byte[] bf = new byte[(int)f.length()];
              new FileInputStream(f).read(bf);
              fileContent = new String(bf, "UTF-8");
          } catch (FileNotFoundException e) {
              // handle file not found exception
          } catch (IOException e) {
              // handle IO-exception
          }
    
    0 讨论(0)
  • 2020-12-01 16:09

    Not quite a one liner and probably obsolete if using JDK 11 as posted by nullpointer. Still usefull if you have a non file input stream

    InputStream inStream = context.getAssets().open(filename);
    Scanner s = new Scanner(inStream).useDelimiter("\\A");
    String string = s.hasNext() ? s.next() : "";
    inStream.close();
    return string;
    
    0 讨论(0)
  • 2020-12-01 16:11

    In Java 8 (no external libraries) you could use streams. This code reads a file and puts all lines separated by ', ' into a String.

    try (Stream<String> lines = Files.lines(myPath)) {
        list = lines.collect(Collectors.joining(", "));
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    
    0 讨论(0)
  • 2020-12-01 16:17

    apache commons-io has:

    String str = FileUtils.readFileToString(file, "utf-8");
    

    But there is no such utility in the standard java classes. If you (for some reason) don't want external libraries, you'd have to reimplement it. Here are some examples, and alternatively, you can see how it is implemented by commons-io or Guava.

    0 讨论(0)
提交回复
热议问题