Hay múltiples formas de escribir y leer un archivo de texto. esto es necesario al tratar con muchas aplicaciones. Hay varias formas de leer un archivo de texto sin formato en Java, por ejemplo, puede usar FileReader , BufferedReader o Scanner para leer un archivo de texto. Cada utilidad proporciona algo especial, por ejemplo, BufferedReader proporciona el almacenamiento en búfer de los datos para una lectura rápida y Scanner proporciona la capacidad de análisis.
Métodos:
Java
// Java Program to illustrate Reading from FileReader // using BufferedReader Class // Importing input output classes import java.io.*; // Main class public class GFG { // main driver method public static void main(String[] args) throws Exception { // File path is passed as parameter File file = new File( "C:\\Users\\pankaj\\Desktop\\test.txt"); // Note: Double backquote is to avoid compiler // interpret words // like \test as \t (ie. as a escape sequence) // Creating an object of BufferedReader class BufferedReader br = new BufferedReader(new FileReader(file)); // Declaring a string variable String st; // Condition holds true till // there is character in a string while ((st = br.readLine()) != null) // Print the string System.out.println(st); } }
Java
// Java Program to Illustrate reading from // FileReader using FileReader class // Importing input output classes import java.io.*; // Main class // ReadingFromFile public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Passing the path to the file as a parameter FileReader fr = new FileReader( "C:\\Users\\pankaj\\Desktop\\test.txt"); // Declaring loop variable int i; // Holds true till there is nothing to read while ((i = fr.read()) != -1) // Print all the content of a file System.out.print((char)i); } }
Java
// Java Program to illustrate // reading from Text File // using Scanner Class import java.io.File; import java.util.Scanner; public class ReadFromFileUsingScanner { public static void main(String[] args) throws Exception { // pass the path to the file as a parameter File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt"); Scanner sc = new Scanner(file); while (sc.hasNextLine()) System.out.println(sc.nextLine()); } }
Java
// Java Program to illustrate reading from FileReader // using Scanner Class reading entire File // without using loop 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.txt"); Scanner sc = new Scanner(file); // we just need to use \\Z as delimiter sc.useDelimiter("\\Z"); System.out.println(sc.next()); } }
Java
// Java program to illustrate reading data from file // using nio.File import java.util.*; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.io.*; public class ReadFileIntoList { public static List<String> readFileInList(String fileName) { List<String> lines = Collections.emptyList(); try { lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); } catch (IOException e) { // do something e.printStackTrace(); } return lines; } public static void main(String[] args) { List l = readFileInList("C:\\Users\\pankaj\\Desktop\\test.java"); Iterator<String> itr = l.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } }
Java
// Java Program to illustrate // reading from text file // as string in Java package io; import java.nio.file.*;; public class ReadTextAsString { public static String readFileAsString(String fileName)throws Exception { String data = ""; data = new String(Files.readAllBytes(Paths.get(fileName))); return data; } public static void main(String[] args) throws Exception { String data = readFileAsString("C:\\Users\\pankaj\\Desktop\\test.java"); System.out.println(data); } }
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA