gpt4 book ai didi

Java读取文件并发送到服务器

转载 作者:行者123 更新时间:2023-12-01 18:33:39 25 4
gpt4 key购买 nike

我需要作为服务器读取文件的内容,然后将读取的数据文件发送给客户端,以便客户端在客户端上打印出来。问题是我找不到从我的java文件和txt文件所在的当前目录读取txt文件的方法或方法。请帮助我。

最佳答案

在java中读取文本文件或文件的方法有很多种。这取决于您需要以哪种格式将文件内容传递到客户端。

这里有一些用java读取文件的方法。
1.使用BufferedReader class

 BufferedReader input =  new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}

2.使用Apache Common IOUtils使用类 IOUtils.toString() 方法。

FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}

3.使用Java中的Scanner类和FileReader

Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));  
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}

扫描仪有多种读取字符串、数字等的方法...

4.在 JAVA 7 中,这是简单读取文本文件的最佳方式

new String(Files.readAllBytes(...))
Files.readAllLines(...)

Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);

请引用此link for more onfomation .

关于Java读取文件并发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com