【问题标题】:Save content of File as String in Java?在Java中将文件的内容保存为字符串?
【发布时间】:2013-06-24 09:44:17
【问题描述】:

我在 java 中使用了一些配置文件和文件阅读器类。 我总是用数组读/写文件,因为我正在处理对象。 这看起来有点像这样:

public void loadUserData(ArrayList<User> arraylist) {
    try {
        List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
        for(String line : lines) {
            String[] userParams = line.split(";");

            String name = userParams[0];
            String number= userParams[1];
            String mail = userParams[2];

            arraylist.add(new User(name, number, mail));
        }   
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这很好用,但是如何将文件的内容保存为一个字符串?

当我读取文件时,我使用的字符串应该与文件的内容完全相同(不使用数组或行拆分)。 我该怎么做?

编辑:

我尝试从文件中读取 SQL 语句,以便稍后将其与 JDBC 一起使用。这就是为什么我需要文件的内容作为单个字符串

【问题讨论】:

标签: java arrays file


【解决方案1】:

这个方法可以用

public static void readFromFile() throws Exception{
        FileReader fIn = new FileReader("D:\\Test.txt");
        BufferedReader br = new BufferedReader(fIn);
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        String text = sb.toString();
        System.out.println(text);

}

【讨论】:

    【解决方案2】:

    我希望这是你需要的:

    public void loadUserData(ArrayList<User> arraylist) {
        StringBuilder sb = new StringBuilder();
        try {
            List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
            for(String line : lines) {
               // String[] userParams = line.split(";");
    
                //String name = userParams[0];
                //String number= userParams[1];
                //String mail = userParams[2];
                sb.append(line);
            }   
            String jdbcString = sb.toString();
            System.out.println("JDBC statements read from file: " + jdbcString );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    或者这个:

    String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
    System.out.println(content);
    

    【讨论】:

    • 谢谢,这正是我需要的!
    • 你不需要在行之间添加一个空格(或其他东西)吗? readAllLines 的 javadoc 没有指定是保留还是丢弃行尾。如果它丢弃它们——这与 LineNumberReader 和其他 Java 方法处理它们的方式一致——我想你会想要在每个附加的行之后添加一个空格。
    • @Paul 正如他所说,该文件包含 sql 脚本,所以我假设它们由“;”分隔。这个想法也是为了帮助移动事情,而不是为提问者做所有事情。我认为他能够移动:-)
    【解决方案3】:

    就这样做吧:

    final FileChannel fc;
    final String theFullStuff;
    
    try (
        fc = FileChannel.open(path, StandardOpenOptions.READ);
    ) {
        final ByteBuffer buf = ByteBuffer.allocate(fc.size());
        fc.read(buf);
        theFullStuff = new String(buf.array(), theCharset);
    }
    

    为胜利而战! :p

    【讨论】:

      【解决方案4】:

      你总是可以创建一个缓冲阅读器,例如

      File anInputFile = new File(/*input path*/);
      FileReader aFileReader = new FileReader(anInputFile);
      BufferedReader reader = new BufferedReader(aFileReader)
      
      String yourSingleString = "";
      String aLine = reader.readLine();
      
      while(aLine != null)
      {
          singleString += aLine + " ";
          aLine = reader.readLine();
      }
      

      【讨论】:

      • 还不错,但 Juned Ahsan 的回答更好......无论如何感谢您的帮助 :)
      • 更喜欢使用StringBuilder。然后使用它的toString() 方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多