A ler um ficheiro de texto simples em Java
parece que existem diferentes maneiras de ler e escrever dados de arquivos em Java.
Quero ler os dados ASCII de um ficheiro. Quais são as formas possíveis e suas diferenças?24 answers
O ASCII é um ficheiro de texto, pelo que poderá usar Os leitores para ler. O Java também suporta a leitura de um ficheiro binário usando InputStreams . Se os arquivos que estão sendo lidos são enormes, então você gostaria de usar um BufferedReader em cima de um FileReader para melhorar o desempenho de leitura.
Ver Este artigo sobre como usar um leitor
Eu também recomendo que você baixe e leia este maravilhoso (ainda livre) livro chamado pensar em JavaEm Java 7:
Novo Texto (Ficheiros.readAllBytes(...)) ou ficheiros.readAllLines (...)
Em Java 8:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
Alguns indicaram que, após o Java 7, você deve usar tentar com os recursos (ou seja, fechar automaticamente) funcionalidades:
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
Quando eu leio textos como este, eu normalmente quero fazer algum tratamento de texto por linha de qualquer maneira, então eu vou para esta implementação.
Embora se Eu quero realmente apenas ler um arquivo em uma String, eu sempre uso Apache Commons IO com a classe IOUtils.método toString (). Você pode dar uma olhada na fonte aqui:
Http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
E ainda mais simples com Java 7:
try(FileInputStream inputStream = new FileInputStream("foo.txt")) {
String everything = IOUtils.toString(inputStream);
// do something with everything string
}
A maneira mais fácil é usar a classe Scanner
em Java e o objeto FileReader. Exemplo simples:
Scanner in = new Scanner(new FileReader("filename.txt"));
Scanner
tem vários métodos para ler em strings, números, etc... Você pode procurar mais informações sobre isso na página de documentação Java.
Por exemplo, ler todo o conteúdo num String
:
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
outString = sb.toString();
Também se precisar de uma codificação específica, pode usar esta em vez de FileReader
:
new InputStreamReader(new FileInputStream(fileUtf8), StandardCharsets.UTF_8)
Aqui está uma solução simples:
String content;
content = new String(Files.readAllBytes(Paths.get("sample.txt")));
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public String readFile(String filename)
{
String content = null;
File file = new File(filename); // For example, foo.txt
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
reader.close();
}
}
return content;
}
Files.lines(Paths.get("/path/to/file.txt")).map(line -> line.split(";"))
de linha única não é uma opção.
Testei o Java 1.8, O Windows 7 e as unidades SSD e HDD.
Eu escrevi seis implementações diferentes:
RawParse: Use BufferedInputStream mais de um FileInputStream e, em seguida, cortar linhas de leitura de byte por byte. Este resultado foi superior qualquer outra abordagem de linha única, mas pode ser muito inconveniente para arquivos não-ASCII.
LineReaderParse : Use um 'buffer' sobre um 'FileReader', leia linha a linha, separe linhas por chamada de texto.dividir(). Isto é aproximadamente 20% mais lento que o rawParse.
LineReaderParseParallel: Este é o mesmo que o lineReaderParse, mas usa vários tópicos. Esta é a opção mais rápida em todos os casos.
NioFilesParse : Usar hipoteca.nio.arquivo.Arquivo.linhas ()
NioAsyncParse : utilizar um filtro assíncrono com um manipulador de completação e um conjunto de linhas.
NioMemoryMappedParse : usar um ficheiro mapeado na memória. Trata-se de uma má ideia, que prevê prazos de execução pelo menos três vezes mais longos do que qualquer outra implementação.
Estes são os tempos médios para ler 204 arquivos de 4 MB cada um em um quad-core i7 e ssd drive. Os arquivos são gerados na altura para evitar o disco cache.rawParse 11.10 sec
lineReaderParse 13.86 sec
lineReaderParseParallel 6.00 sec
nioFilesParse 13.52 sec
nioAsyncParse 16.06 sec
nioMemoryMappedParse 37.68 sec
Encontrei uma diferença menor do que esperava entre correr num SSD ou num HDD ser o SSD aproximadamente 15% mais rápido. Isto pode ser porque os arquivos são gerados em um HDD não mutilado e eles são lidos sequencialmente, portanto, a unidade de fiação pode executar quase como um SSD.
Fiquei surpreendido com o baixo desempenho da implementação nioAsyncParse. Ou eu implementei algo da maneira errada ou a implementação multi-thread usando NIO e um controlador de completação executa o mesmo (ou ainda pior) do que uma implementação de linha única com o java.io API. Além disso, o processamento assíncrono com um CompletionHandler é muito mais longo em linhas de código e difícil de implementar corretamente do que uma implementação reta em fluxos antigos.Agora as seis implementações seguidas por uma classe contendo todas elas mais um método parametrizável main() que permite jogar com o número de arquivos, Tamanho de arquivo e grau de concorrência. Note - se que o o tamanho dos arquivos varia mais menos 20%. Isto é para evitar qualquer efeito devido a todos os arquivos serem exatamente do mesmo tamanho.
RawParse
public void rawParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
overrunCount = 0;
final int dl = (int) ';';
StringBuffer lineBuffer = new StringBuffer(1024);
for (int f=0; f<numberOfFiles; f++) {
File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
FileInputStream fin = new FileInputStream(fl);
BufferedInputStream bin = new BufferedInputStream(fin);
int character;
while((character=bin.read())!=-1) {
if (character==dl) {
// Here is where something is done with each line
doSomethingWithRawLine(lineBuffer.toString());
lineBuffer.setLength(0);
}
else {
lineBuffer.append((char) character);
}
}
bin.close();
fin.close();
}
}
public final void doSomethingWithRawLine(String line) throws ParseException {
// What to do for each line
int fieldNumber = 0;
final int len = line.length();
StringBuffer fieldBuffer = new StringBuffer(256);
for (int charPos=0; charPos<len; charPos++) {
char c = line.charAt(charPos);
if (c==DL0) {
String fieldValue = fieldBuffer.toString();
if (fieldValue.length()>0) {
switch (fieldNumber) {
case 0:
Date dt = fmt.parse(fieldValue);
fieldNumber++;
break;
case 1:
double d = Double.parseDouble(fieldValue);
fieldNumber++;
break;
case 2:
int t = Integer.parseInt(fieldValue);
fieldNumber++;
break;
case 3:
if (fieldValue.equals("overrun"))
overrunCount++;
break;
}
}
fieldBuffer.setLength(0);
}
else {
fieldBuffer.append(c);
}
}
}
LineReaderParse
public void lineReaderParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
String line;
for (int f=0; f<numberOfFiles; f++) {
File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
FileReader frd = new FileReader(fl);
BufferedReader brd = new BufferedReader(frd);
while ((line=brd.readLine())!=null)
doSomethingWithLine(line);
brd.close();
frd.close();
}
}
public final void doSomethingWithLine(String line) throws ParseException {
// Example of what to do for each line
String[] fields = line.split(";");
Date dt = fmt.parse(fields[0]);
double d = Double.parseDouble(fields[1]);
int t = Integer.parseInt(fields[2]);
if (fields[3].equals("overrun"))
overrunCount++;
}
LineReaderParseParallel
public void lineReaderParseParallel(final String targetDir, final int numberOfFiles, final int degreeOfParalelism) throws IOException, ParseException, InterruptedException {
Thread[] pool = new Thread[degreeOfParalelism];
int batchSize = numberOfFiles / degreeOfParalelism;
for (int b=0; b<degreeOfParalelism; b++) {
pool[b] = new LineReaderParseThread(targetDir, b*batchSize, b*batchSize+b*batchSize);
pool[b].start();
}
for (int b=0; b<degreeOfParalelism; b++)
pool[b].join();
}
class LineReaderParseThread extends Thread {
private String targetDir;
private int fileFrom;
private int fileTo;
private DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private int overrunCounter = 0;
public LineReaderParseThread(String targetDir, int fileFrom, int fileTo) {
this.targetDir = targetDir;
this.fileFrom = fileFrom;
this.fileTo = fileTo;
}
private void doSomethingWithTheLine(String line) throws ParseException {
String[] fields = line.split(DL);
Date dt = fmt.parse(fields[0]);
double d = Double.parseDouble(fields[1]);
int t = Integer.parseInt(fields[2]);
if (fields[3].equals("overrun"))
overrunCounter++;
}
@Override
public void run() {
String line;
for (int f=fileFrom; f<fileTo; f++) {
File fl = new File(targetDir+filenamePreffix+String.valueOf(f)+".txt");
try {
FileReader frd = new FileReader(fl);
BufferedReader brd = new BufferedReader(frd);
while ((line=brd.readLine())!=null) {
doSomethingWithTheLine(line);
}
brd.close();
frd.close();
} catch (IOException | ParseException ioe) { }
}
}
}
NioFilesParse
public void nioFilesParse(final String targetDir, final int numberOfFiles) throws IOException, ParseException {
for (int f=0; f<numberOfFiles; f++) {
Path ph = Paths.get(targetDir+filenamePreffix+String.valueOf(f)+".txt");
Consumer<String> action = new LineConsumer();
Stream<String> lines = Files.lines(ph);
lines.forEach(action);
lines.close();
}
}
class LineConsumer implements Consumer<String> {
@Override
public void accept(String line) {
// What to do for each line
String[] fields = line.split(DL);
if (fields.length>1) {
try {
Date dt = fmt.parse(fields[0]);
}
catch (ParseException e) {
}
double d = Double.parseDouble(fields[1]);
int t = Integer.parseInt(fields[2]);
if (fields[3].equals("overrun"))
overrunCount++;
}
}
}
NioAsyncParse
public void nioAsyncParse(final String targetDir, final int numberOfFiles, final int numberOfThreads, final int bufferSize) throws IOException, ParseException, InterruptedException {
ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(numberOfThreads);
ConcurrentLinkedQueue<ByteBuffer> byteBuffers = new ConcurrentLinkedQueue<ByteBuffer>();
for (int b=0; b<numberOfThreads; b++)
byteBuffers.add(ByteBuffer.allocate(bufferSize));
for (int f=0; f<numberOfFiles; f++) {
consumerThreads.acquire();
String fileName = targetDir+filenamePreffix+String.valueOf(f)+".txt";
AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get(fileName), EnumSet.of(StandardOpenOption.READ), pool);
BufferConsumer consumer = new BufferConsumer(byteBuffers, fileName, bufferSize);
channel.read(consumer.buffer(), 0l, channel, consumer);
}
consumerThreads.acquire(numberOfThreads);
}
class BufferConsumer implements CompletionHandler<Integer, AsynchronousFileChannel> {
private ConcurrentLinkedQueue<ByteBuffer> buffers;
private ByteBuffer bytes;
private String file;
private StringBuffer chars;
private int limit;
private long position;
private DateFormat frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public BufferConsumer(ConcurrentLinkedQueue<ByteBuffer> byteBuffers, String fileName, int bufferSize) {
buffers = byteBuffers;
bytes = buffers.poll();
if (bytes==null)
bytes = ByteBuffer.allocate(bufferSize);
file = fileName;
chars = new StringBuffer(bufferSize);
frmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
limit = bufferSize;
position = 0l;
}
public ByteBuffer buffer() {
return bytes;
}
@Override
public synchronized void completed(Integer result, AsynchronousFileChannel channel) {
if (result!=-1) {
bytes.flip();
final int len = bytes.limit();
int i = 0;
try {
for (i = 0; i < len; i++) {
byte by = bytes.get();
if (by=='\n') {
// ***
// The code used to process the line goes here
chars.setLength(0);
}
else {
chars.append((char) by);
}
}
}
catch (Exception x) {
System.out.println(
"Caught exception " + x.getClass().getName() + " " + x.getMessage() +
" i=" + String.valueOf(i) + ", limit=" + String.valueOf(len) +
", position="+String.valueOf(position));
}
if (len==limit) {
bytes.clear();
position += len;
channel.read(bytes, position, channel, this);
}
else {
try {
channel.close();
}
catch (IOException e) {
}
consumerThreads.release();
bytes.clear();
buffers.add(bytes);
}
}
else {
try {
channel.close();
}
catch (IOException e) {
}
consumerThreads.release();
bytes.clear();
buffers.add(bytes);
}
}
@Override
public void failed(Throwable e, AsynchronousFileChannel channel) {
}
};
IMPLEMENTAÇÃO INTEGRAL DE TODOS Processos
Https://github.com/sergiomt/javaiobenchmark/blob/master/FileReadBenchmark.java
Os métodos dentro org.apache.commons.io.FileUtils
pode também ser muito útil, por exemplo:
/**
* Reads the contents of a file line by line to a List
* of Strings using the default encoding for the VM.
*/
static List readLines(File file)
Usando BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file = new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine()) != null){
System.out.println(st);
}
}
}
Usando Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Usando FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while ((i=fr.read()) != -1){
System.out.print((char) i);
}
}
}
Leia o ficheiro inteiro sem um loop usando a classe Scanner
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc = new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
for(String line: FileUtils.readLines("my-text-file"))
System.out.println(line);
Abaixo está uma linha de fazê-lo da forma Java 8. Assumindo que o ficheiro text.txt
está na raiz do directório do Projecto do Eclipse.
Files.lines(Paths.get("text.txt")).collect(Collectors.toList());
Usando O Sistema De Leitura Tamponada:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
BufferedReader br;
try {
br = new BufferedReader(new FileReader("/fileToRead.txt"));
try {
String x;
while ( (x = br.readLine()) != null ) {
// Printing out each line in the file
System.out.println(x);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
System.out.println(e);
e.printStackTrace();
}
Isto é basicamente o mesmo que a resposta de Jesus Ramos, excepto comficheiro em vez deFileReader mais iteração para passar pelo conteúdo do ficheiro.
Scanner in = new Scanner(new File("filename.txt"));
while (in.hasNext()) { // Iterates each line in the file
String line = in.nextLine();
// Do something with line
}
in.close(); // Don't forget to close resource leaks
... lances FileNotFoundException
Provavelmente não tão rápido como com o I/O tamponado, mas bastante conciso:
String content;
try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
content = scanner.next();
}
O padrão \Z
diz ao Scanner
que o delimitador é EOF.
Documentei 15 maneiras de ler um ficheiro em Java e depois testei - as para a velocidade com vários tamanhos de ficheiros-de 1 KB a 1 GB e aqui estão as três principais maneiras de fazer isto:
-
java.nio.file.Files.readAllBytes()
Testado para trabalhar em Java 7, 8 e 9.
import java.io.File; import java.io.IOException; import java.nio.file.Files; public class ReadFile_Files_ReadAllBytes { public static void main(String [] pArgs) throws IOException { String fileName = "c:\\temp\\sample-10KB.txt"; File file = new File(fileName); byte [] fileBytes = Files.readAllBytes(file.toPath()); char singleChar; for(byte b : fileBytes) { singleChar = (char) b; System.out.print(singleChar); } } }
-
java.io.BufferedReader.readLine()
Testado para trabalhar em Java 7, 8, 9.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFile_BufferedReader_ReadLine { public static void main(String [] args) throws IOException { String fileName = "c:\\temp\\sample-10KB.txt"; FileReader fileReader = new FileReader(fileName); try (BufferedReader bufferedReader = new BufferedReader(fileReader)) { String line; while((line = bufferedReader.readLine()) != null) { System.out.println(line); } } } }
-
Isto foi testado para funcionar em Java 8 e 9, mas não funcionará em Java 7 por causa da expressão lambda. requisito.java.nio.file.Files.lines()
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.stream.Stream; public class ReadFile_Files_Lines { public static void main(String[] pArgs) throws IOException { String fileName = "c:\\temp\\sample-10KB.txt"; File file = new File(fileName); try (Stream linesStream = Files.lines(file.toPath())) { linesStream.forEach(line -> { System.out.println(line); }); } } }
Http://download.oracle.com/javase/tutorial/essential/io/file.html
A forma mais simples de ler os dados de um ficheiro em Java é fazer uso da classe para ler o ficheiro e a classe Scanner para ler o conteúdo do ficheiro.
public static void main(String args[])throws Exception
{
File f = new File("input.txt");
takeInputIn2DArray(f);
}
public static void takeInputIn2DArray(File f) throws Exception
{
Scanner s = new Scanner(f);
int a[][] = new int[20][20];
for(int i=0; i<20; i++)
{
for(int j=0; j<20; j++)
{
a[i][j] = s.nextInt();
}
}
}
PS: não se esqueça de importar java.util.* ; para que o Scanner funcione.
Com o seguinte código,
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class InputReader{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s="";
while((s=br.readLine())!=null){
System.out.println(s);
}
}
}
Vá em frente e fale com:
java InputReader < input.txt
Isto iria ler o conteúdo do input.txt
e imprimi-lo no seu console.
Você também pode fazer o seu System.out.println()
para escrever para um arquivo específico através do linha de comandos:
java InputReader < input.txt > output.txt
Isto seria lido de input.txt
e escrito para output.txt
.
Para aplicações web Maven baseadas no JSF, basta usar o ClassLoader e a pasta Resources
para ler em qualquer ficheiro que quiser:
- Coloque QUALQUER ficheiro que queira ler na pasta de recursos.
-
Coloque a dependência do Apache Commons IO no seu POM:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency>
-
Use o código abaixo para lê-lo (por exemplo, abaixo está a ler em A.ficheiro json):
String metadata = null; FileInputStream inputStream; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); inputStream = (FileInputStream) loader .getResourceAsStream("/metadata.json"); metadata = IOUtils.toString(inputStream); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metadata;
Você pode fazer o mesmo para arquivos de texto, .properties files, XSD schemas, etc.
Goiaba fornece uma linha única para isto:
import com.google.common.base.Charsets;
import com.google.common.io.Files;
String contents = Files.toString(filePath, Charsets.UTF_8);
Cactoos dá-lhe uma linha declarativa:
new TextOf(new File("a.txt")).asString();
Pode usar as linhas de leitura e o método join
para obter todo o conteúdo do ficheiro numa linha:
String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));
Ele usa codificação UTF-8 por padrão, que lê os dados ASCII corretamente.
Também pode usar readAllBytes:
String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);
Eu acho que readAllBytes é mais rápido e mais preciso, porque não substitui nova linha por \n
e também nova linha pode ser \r\n
. Depende de suas necessidades Qual é adequado.
Use Java kiss se se trata de simplicidade de Estrutura:
import static kiss.API.*;
class App {
void run() {
String line;
try (Close in = inOpen("file.dat")) {
while ((line = readLine()) != null) {
println(line);
}
}
}
}
As classes de fluxo buffer são muito mais eficazes na prática, tanto que o NIO.2 API inclui métodos que devolvem especificamente essas classes de fluxo, em parte para encorajá-lo sempre a usar fluxos tamponados em sua aplicação.
Aqui está um exemplo:
Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
// Read from the stream
String currentLine = null;
while ((currentLine = reader.readLine()) != null)
//do your code here
} catch (IOException e) {
// Handle file I/O exception...
}
Pode substituir este código
BufferedReader reader = Files.newBufferedReader(path);
Com
BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));
Eu recomendo Este artigo para aprender os principais usos de Java NIO e IO.
Este código que programei é muito mais rápido para ficheiros muito grandes:
public String readDoc(File f) {
String text = "";
int read, N = 1024 * 1024;
char[] buffer = new char[N];
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
while(true) {
read = br.read(buffer, 0, N);
text += new String(buffer, 0, read);
if(read < N) {
break;
}
}
} catch(Exception ex) {
ex.printStackTrace();
}
return text;
}