java怎么读取本地json文件

55次阅读
没有评论

共计 949 个字符,预计需要花费 3 分钟才能阅读完成。

Java 可以使用 java.io.FileReaderjava.nio.file.Files 类来读取本地的 JSON 文件。

  1. 使用 java.io.FileReader 类:
import java.io.FileReader;
import java.io.IOException;

public class ReadJsonFile {public static void main(String[] args) {try {FileReader reader = new FileReader("path/to/file.json");
            int character;
            StringBuilder jsonString = new StringBuilder();
            
            while ((character = reader.read()) != -1) {jsonString.append((char) character);
            }
            
            reader.close();
            
            System.out.println(jsonString.toString());
        } catch (IOException e) {e.printStackTrace();
        }
    }
}

path/to/file.json 替换为你的 JSON 文件的路径。

  1. 使用 java.nio.file.Files 类:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ReadJsonFile {public static void main(String[] args) {try {Path filePath = Paths.get("path/to/file.json");
            String jsonString = Files.readString(filePath);
            
            System.out.println(jsonString);
        } catch (IOException e) {e.printStackTrace();
        }
    }
}

同样,将 path/to/file.json 替换为你的 JSON 文件的路径。

这两种方法都可以读取本地的 JSON 文件并将其内容以字符串形式输出。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-12发表,共计949字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)