Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中,将整个文本文件转换为字符串_Java_File_File Io - Fatal编程技术网

在Java中,将整个文本文件转换为字符串

在Java中,将整个文本文件转换为字符串,java,file,file-io,Java,File,File Io,Java是否像C#一样有一行指令来读取文本文件 我的意思是,在Java中有类似的东西吗 String data = System.IO.File.ReadAllText("path to file"); 如果不是。。。做这件事的“最佳方式”是什么 编辑: 我更喜欢Java标准库中的一种方法。。。我不能使用第三方库。不能在主Java库中使用,但您可以使用: 或阅读以下文字: List<String> lines = Files.readLines( new File("path.t

Java是否像C#一样有一行指令来读取文本文件

我的意思是,在Java中有类似的东西吗

String data = System.IO.File.ReadAllText("path to file");
如果不是。。。做这件事的“最佳方式”是什么

编辑:

我更喜欢Java标准库中的一种方法。。。我不能使用第三方库。

不能在主Java库中使用,但您可以使用:

或阅读以下文字:

List<String> lines = Files.readLines( new File("path.txt"), Charsets.UTF_8 );
List lines=Files.readLines(新文件(“path.txt”)、Charsets.UTF_8);
当然,我确信还有其他第三方库可以让它变得同样简单-我只是最熟悉番石榴。

有:


但是在标准java类中没有这样的实用程序。如果(出于某种原因)不需要外部库,则必须重新实现它。下面是一些示例,或者,您可以看到commons io或Guava是如何实现它的。

Java 11通过以下示例代码为该用例添加了支持:

Files.readString(Path.of("/your/directory/path/file.txt"));
在Java 11之前,使用标准库的典型方法如下:

public static String readStream(InputStream is) {
    StringBuilder sb = new StringBuilder(512);
    try {
        Reader r = new InputStreamReader(is, "UTF-8");
        int c = 0;
        while ((c = r.read()) != -1) {
            sb.append((char) c);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}
注:

  • 要从文件中读取文本,请使用FileInputStream
  • 如果性能很重要并且您正在读取大文件,建议将流包装在BufferedInputStream中
  • 调用者应关闭流

Java 7改进了类的这种令人遗憾的状态(不要与Guava的混淆),您可以从一个文件中获取所有行(无需外部库),其中包括:

List<String> fileLines = Files.readAllLines(path, StandardCharsets.UTF_8);

如果你需要一个干净的JDK,这是非常好的。也就是说,为什么要编写没有Guava的Java?

不需要外部库。文件内容将在转换为字符串之前进行缓冲

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
  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
      }

不需要外部库。文件内容将在转换为字符串之前进行缓冲

Path path = FileSystems.getDefault().getPath(directory, filename);
String fileContent = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
  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
      }

Java8(没有外部库)中,可以使用流。这段代码读取一个文件,并将所有以“,”分隔的行放入一个字符串中

try (Stream<String> lines = Files.lines(myPath)) {
    list = lines.collect(Collectors.joining(", "));
} catch (IOException e) {
    LOGGER.error("Failed to load file.", e);
}
try(streamlines=Files.lines(myPath)){
list=lines.collect(collector.joining(“,”);
}捕获(IOE异常){
LOGGER.error(“加载文件失败”,e);
}

这里有三种方法可以在一行中读取文本文件,而不需要循环。我有文档记录,这些都来自那篇文章

请注意,您仍然必须遍历返回的列表,即使读取文件内容的实际调用只需要1行,而不需要循环

1) java.nio.file.Files.readAllLines()-默认编码

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines_Encoding {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    List  fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}
2) java.nio.file.Files.readAllLines()-显式编码

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    List  fileLinesList = Files.readAllLines(file.toPath());

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class ReadFile_Files_ReadAllLines_Encoding {
  public static void main(String [] pArgs) throws IOException {
    String fileName = "c:\\temp\\sample-10KB.txt";
    File file = new File(fileName);

    //use UTF-8 encoding
    List  fileLinesList = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);

    for(String line : fileLinesList) {
      System.out.println(line);
    }
  }
}
3) java.nio.file.Files.readAllBytes()


使用JDK/11,您可以使用
文件将
路径中的完整文件作为字符串读取。readString(路径路径)

try {
    String fileContent = Files.readString(Path.of("/foo/bar/gus"));
} catch (IOException e) {
    // handle exception in i/o
}
JDK中的方法文档如下所示:

/**
 * Reads all content from a file into a string, decoding from bytes to characters
 * using the {@link StandardCharsets#UTF_8 UTF-8} {@link Charset charset}.
 * The method ensures that the file is closed when all content have been read
 * or an I/O error, or other runtime exception, is thrown.
 *
 * <p> This method is equivalent to:
 * {@code readString(path, StandardCharsets.UTF_8) }
 *
 * @param   path the path to the file
 *
 * @return  a String containing the content read from the file
 *
 * @throws  IOException
 *          if an I/O error occurs reading from the file or a malformed or
 *          unmappable byte sequence is read
 * @throws  OutOfMemoryError
 *          if the file is extremely large, for example larger than {@code 2GB}
 * @throws  SecurityException
 *          In the case of the default provider, and a security manager is
 *          installed, the {@link SecurityManager#checkRead(String) checkRead}
 *          method is invoked to check read access to the file.
 *
 * @since 11
 */
public static String readString(Path path) throws IOException 
/**
*将文件中的所有内容读入字符串,从字节解码为字符
*使用{@link-standardcharset}UTF#u 8 UTF-8}{@link-Charset-Charset}。
*该方法确保在读取所有内容后关闭文件
*或引发I/O错误或其他运行时异常。
*
*此方法相当于:
*{@code readString(路径,StandardCharsets.UTF_8)}
*
*@param path文件的路径
*
*@返回包含从文件中读取的内容的字符串
*
*@抛出异常
*如果从文件读取时发生I/O错误,或出现格式错误或
*读取不可映射的字节序列
*@抛出内存错误
*如果文件非常大,例如大于{@code 2GB}
*@抛出安全异常
*在默认提供程序的情况下,需要一个安全管理器
*已安装{@link SecurityManager#checkRead(String)checkRead}
*方法以检查对文件的读取访问。
*
*@自11日起
*/
公共静态字符串readString(路径路径)引发IOException

如果使用nullpointer发布的JDK 11,则不是一行程序,可能已经过时。如果您有非文件输入流,仍然有用

InputStream inStream = context.getAssets().open(filename);
Scanner s = new Scanner(inStream).useDelimiter("\\A");
String string = s.hasNext() ? s.next() : "";
inStream.close();
return string;

我会使用
FileUtils.readFileToString(文件,编码)
版本-最好推荐好习惯!缓冲读取器有一个读取行,这比一次读取一个字符要好。如果您使用BufferedInputStream,它不会有什么不同。它会将最后一个(-1)添加到字符串中。不,它不会。它在while条件(c!=-1)下检查,这真的不酷。返回字符串总是以-1结尾,因为在while循环中进行了粗心的编码。注意:抛出了一个
不支持的codingexception
。您应该更喜欢构造函数以及或Guava中的常量。这是一个纯代码的答案,您的答案没有提到在将其转换为字符串之前需要对所有字节进行缓冲(即,它不是非常高效的内存)。现在是您可以这样做的时候了。我不认为读行和放弃行尾编码有什么意义。但前提是您从未遵循I/O流教程,不了解如何处理错误,并且希望在将所有字符转换为字符串之前将其复制到缓冲区。请描述您的答案,仅代码的答案通常不会向上投票。第二个示例中的路径类型为path,可以从var path=path.get(filePathAsString)的字符串中检索;所有
文件
方法都使用
路径
;看
Paths.get()
只是获取
Path
实例的一种方法。实例可能重复