Java 11 - Files.readString()
java 11 提供了readString()方法,只需一行就能读取文件内容为字符串。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteToFile
{
public static void main(String[] args) throws IOException
{
Path fileName = Path.of("demo.txt");
String content = "hello world !!";
Files.writeString(fileName, content);
String actual = Files.readString(fileName);
System.out.println(actual);
}
}
Java 8 - Files.lines()
lines()方法会从文件读取所有行到流。
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ReadFileToString
{
public static void main(String[] args)
{
String filePath = "c:/temp/data.txt";
System.out.println( readLineByLineJava8( filePath ) );
}
//Read file content into string with - Files.lines(Path path, Charset cs)
private static String readLineByLineJava8(String filePath)
{
StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines( Paths.get(filePath), StandardCharsets.UTF_8))
{
stream.forEach(s -> contentBuilder.append(s).append("\n"));
}
catch (IOException e)
{
e.printStackTrace();
}
return contentBuilder.toString();
}
}
Java 7 - Files.readAllBytes()
readAllBytes()方法从文件中读取所有字节。
public class ReadFileToString
{
public static void main(String[] args)
{
String filePath = "c:/temp/data.txt";
System.out.println( readAllBytesJava7( filePath ) );
}
//Read file content into string with - Files.readAllBytes(Path path)
private static String readAllBytesJava7(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
}
Java 6 - BufferedReader
BufferedReader一行行读文件。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileToString
{
public static void main(String[] args)
{
String filePath = "c:/temp/data.txt";
System.out.println( usingBufferedReader( filePath ) );
}
//Read file content into string with - using BufferedReader and FileReader
//You can use this if you are still not using Java 8
private static String usingBufferedReader(String filePath)
{
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(filePath)))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null)
{
contentBuilder.append(sCurrentLine).append("\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
return contentBuilder.toString();
}
}