简体   繁体   English

在Java中读取文件时获得相同的内容

[英]same content is getting while reading a file in java

I have created a FileReader object. 我创建了一个FileReader对象。

public String getFileContent(){

   StringBuilder filecontent= new StringBuilder();

   FileReader fileReader =  new FileReader("D:/myfile");

   BufferedReader bufferedReader = new BufferedReader(fileReader);


   while((line = bufferedReader.readLine()) != null) {

      filecontent.append(bufferedReader.readLine());

   }    

   return filecontent.toString;
}

The problem I face is that the function always returns the same string even if the file content is changed. 我面临的问题是,即使文件内容已更改,该函数也始终返回相同的字符串。

Anyone to help??? 有人帮忙吗???

append the variable line since you store it to that variable. 由于将变量line存储到该变量中,因此请追加该变量line The problem is you're calling the readline() twice 问题是您两次调用readline()

like this: 像这样:

while((line = bufferedReader.readLine()) != null) { 
      filecontent.append(line); 
 }  

You received an answer already, but it seems that what you're doing could be achieved way better in Java 8: 您已经收到了答案,但是似乎可以在Java 8中更好地实现您正在做的事情:

Path filePath = Paths.get("D:/myfile");
byte[] fileBytes = Files.readAllBytes(filePath);
Charset fileEncoding = StandardCharsets.UTF_8;
String fileContents = new String(fileBytes, fileEncoding);

If you're not on Java 8, you can use Apache Commons IO's FileUtils to get the String : 如果您使用的不是Java 8,则可以使用Apache Commons IO的FileUtils来获取String

File file = new File("D:/myfile");
String fileContents = FileUtils.readFileToString(file);

My advice here is leverage the JDK and existing libraries as much as possible. 我的建议是尽可能利用JDK和现有库。 It leads to cleaner code that is easier to maintain. 它导致更干净的代码,更易于维护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM