Java print file contents

Java print file contents

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java
Читайте также:  Php line start with

Источник

Print Contents of Text File to Screen in Java

  1. Scanner Class in Java
  2. BufferedReader Class in Java
  3. FileReader Class in Java

This article shows ways to use Java to print the contents of a text file on the screen. In Java, there are several ways to read a text file.

It is necessary when working with a large number of applications. You may read a plain text file in Java using FileReader , BufferedReader , or Scanner .

Every utility, for example, has something special to offer. With BufferedReader , data is buffered for fast reading, while parsing is done with Scanner .

Scanner Class in Java

The Scanner parses primitive types and strings using regular expressions. A Scanner divides its input into tokens using a delimiter pattern that matches whitespace by default.

The created tokens can then be translated into other values using the below-mentioned procedures. The Scanner class is demonstrated in the example below.

To use the Scanner class, we’ve imported libraries.

import java.io.File; import java.util.Scanner; 
import java.io.File; import java.util.Scanner; public class Main   public static void main(String[] args) throws Exception    File testfile = new File("C:\\Users\\shanii\\Desktop\\read.txt");  Scanner scnr = new Scanner(testfile);   while (scnr.hasNextLine())  System.out.println(scnr.nextLine());  > > 

BufferedReader Class in Java

This approach employs a stream of characters to read text. It buffers characters, arrays, and lines for faster reading.

The buffer size can be changed or is set to be utilized by default. For the most part, the default settings are basic.

Every read request to a Reader is usually followed by a read request to the underlying character or byte stream. As a result, as shown below, it’s a good idea to wrap a BufferedReader through any Reader whose read() operations are likely to be costly, such as FileReaders and InputStreamReaders .

BufferedReader br = new BufferedReader(Reader br, int size); 
  1. To begin, you have to import the library java.io* .
  2. In the below example, read.txt will be the file you want to read.
import java.io.*;  public class Shani   public static void main(String[] args) throws Exception    File testfile = new File("C:\\Users\\shanii\\Desktop\\read.txt");  BufferedReader br= new BufferedReader(new FileReader(testfile));  String z;  while ((z = br.readLine()) != null)  System.out.println(z);  > > 

FileReader Class in Java

This class makes it easy to read character files. The constructors of this class presume that the default character encoding and byte-buffer size are adequate.

  1. FileReader ( File file) — creates a new FileReader from the specified File .
  2. FileReader ( FileDescriptor fdt) — Given the FileDescriptor to read from, creates a new FileReader .
  3. FileReader (String fileName ) — creates a new FileReader with the specified file name.

Let’s look at FileReader as an example to help us understand.

import java.io.*;  public class Shani    // Main driver method  public static void main(String[] args) throws Exception    FileReader frdr = new FileReader("C:\\Users\\shanii\\Desktop\\read.txt");  int z;  while ((z = frdr.read()) != -1)  System.out.print((char)z);  > > 

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I’m a senior in an undergraduate program for a bachelor’s degree in Information Technology.

Related Article — Java Print

Источник

Java print contents of text file to screen

But to give you something to contrast your code with, the following will read a file provided as an argument and then read it char-by-char (i.e. it supports unicode characters), printing that character out as it goes. Also, you should keep reading until end of file, so you probably wouldn’t be able to write a -style of loop.

This article shows ways to use Java to print the contents of a text file on the screen. In Java, there are several ways to read a text file.

It is necessary when working with a large number of applications. You may read a plain text file in Java using FileReader , BufferedReader , or Scanner .

Every utility, for example, has something special to offer. With BufferedReader , data is buffered for fast reading, while parsing is done with Scanner .

Scanner Class in Java

The Scanner parses primitive types and strings using regular expressions. A Scanner divides its input into tokens using a delimiter pattern that matches whitespace by default.

The created tokens can then be translated into other values using the below-mentioned procedures. The Scanner class is demonstrated in the example below.

To use the Scanner class, we’ve imported libraries.

import java.io.File; import java.util.Scanner; 
import java.io.File; import java.util.Scanner; public class Main < public static void main(String[] args) throws Exception < File testfile = new File("C:\\Users\\shanii\\Desktop\\read.txt"); Scanner scnr = new Scanner(testfile); while (scnr.hasNextLine()) System.out.println(scnr.nextLine()); >> 

BufferedReader Class in Java

This approach employs a stream of characters to read text. It buffers characters, arrays, and lines for faster reading.

The buffer size can be changed or is set to be utilized by default. For the most part, the default settings are basic.

Every read request to a Reader is usually followed by a read request to the underlying character or byte stream. As a result, as shown below, it’s a good idea to wrap a BufferedReader through any Reader whose read() operations are likely to be costly, such as FileReaders and InputStreamReaders .

BufferedReader br = new BufferedReader(Reader br, int size); 

Let’s look at BufferedReader as an example to help us understand.

  1. To begin, you have to import the library java.io* .
  2. In the below example, read.txt will be the file you want to read.
import java.io.*; public class Shani < public static void main(String[] args) throws Exception < File testfile = new File("C:\\Users\\shanii\\Desktop\\read.txt"); BufferedReader br= new BufferedReader(new FileReader(testfile)); String z; while ((z = br.readLine()) != null) System.out.println(z); >> 

FileReader Class in Java

The following are the constructors specified in this class.

  1. FileReader ( File file) — creates a new FileReader from the specified File .
  2. FileReader ( FileDescriptor fdt) — Given the FileDescriptor to read from, creates a new FileReader .
  3. FileReader (String fileName ) — creates a new FileReader with the specified file name.

Let’s look at FileReader as an example to help us understand.

import java.io.*; public class Shani < // Main driver method public static void main(String[] args) throws Exception < FileReader frdr = new FileReader("C:\\Users\\shanii\\Desktop\\read.txt"); int z; while ((z = frdr.read()) != -1) System.out.print((char)z); >> 

Java Print

Java: print contents of text file to screen, I have a text file named foo.txt, and its contents are as below: this is text How would I print this exact file to the screen in Java 7? Stack Overflow. Java: print contents of text file to screen. Ask Question Asked 9 years, 4 months ago. Modified 2 years, 8 months ago. Viewed 166k times Code sampleScanner input = new Scanner(new File(«foo.txt»));while (input.hasNextLine()) Feedback

Printing the exact content of a text file in Java

As @Joachim Sauer and @bmargulies indicated, without more details, we can’t really tell you exactly what the problem is.

But to give you something to contrast your code with, the following will read a file provided as an argument and then read it char-by-char (i.e. it supports unicode characters), printing that character out as it goes. If this doesn’t accomplish your goal, a specific (small) example of input that fails for you would be nice.

import java.io.*; class printout < public static void main (String[] args) < if (args.length < 1) < System.err.println ("Usage: printout "); System.exit (1); > File sourceFile = new File (args[0]); FileReader fr = null; try < fr = new FileReader (sourceFile); int inChar; while ( (inChar = fr.read()) != -1 ) < System.out.printf ("%c", inChar); >> catch (IOException e) < System.err.printf ("Failure while reading %s: %s\n", args[0], e.getMessage()); e.printStackTrace (); >finally < try < if (fr != null) < fr.close (); >> catch (IOException e) < System.err.printf ("Error closing file reader: %s\n", e.getMessage()); e.printStackTrace (); >> > > 

With printing you mean this? Then try replacing all \t with e.g. 4 spaces and \n with new drawString calls.

Another possibility is to fill a JTextComponent or JEditorPane and print it.

If you meant normal sys-out-printing then see the answer of RTBarnard + use:

BufferedReader reader = new BufferedReader( new InputStreamReader(new FileReader("file.txt"), "UTF-8"); reader.readLine(); etc 

This is easier in my eyes and you will always use the correct encoding

FileUtils.readFileToString(file) should do (from commons-io), but be careful with larger files, because they may take up the whole memory that’s allocated for the VM.

Another thing you can use is IOUtils.copy(new FileInputStream(..), outputStream) ; — this will transfer everything from one stream (a file stream in this case) to another, output stream.

Print Contents of Text File to Screen in Java, This article shows ways to use Java to print the contents of a text file on the screen. In Java, there are several ways to read a text file. It is necessary when working with a large number of applications. You may read a plain text file in Java using FileReader, BufferedReader, or Scanner. Every utility, for example, has …

Java — Printing random words from a text file [duplicate]

Read the file and store it into a List

FileInputStream in = new FileInputStream("yourfile.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; List filearray = new ArrayList(); while ((strLine = br.readLine()) != null) < for (int j = 0; j < myarray.length; j++)< // get the whole line and split into words String[] s = br.readLine().split(" "); // put each word in the list for (String s : strings) filearray.add(); >> in.close(); 

Get the List.size() and pick a random number

int size = filearray.size(); Random rn = new Random(); int randomWord = rn.nextInt(size); 
System.out.println("Random word is: " + filearray.get(randomWord)); 

NOTE: repeat this as many times as you want.

Printing the exact content of a text file in Java, Another possibility is to fill a JTextComponent or JEditorPane and print it. If you meant normal sys-out-printing then see the answer of RTBarnard + use: BufferedReader reader = new BufferedReader ( new InputStreamReader (new FileReader («file.txt»), «UTF-8»); reader.readLine (); etc. This is easier in my eyes …

Java program read and print to text file using Scanner

You don’t need that for loop over there. Also, you want to read line by line. Here is quick fix of your code:

public class Bags < public static void main(String[] args) throws IOException < FileInputStream fileinput = new FileInputStream("input.txt"); FileOutputStream fileoutput = new FileOutputStream("output.txt"); Scanner infile = new Scanner(fileinput); PrintWriter pw = new PrintWriter(fileoutput); double total = 0, line = 0; int bags = 0, count = 0; pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost"); while(infile.hasNext())< int i = infile.nextInt(); if (i else if (i else < total = ((80.50) * 4) + ((75.50) * (i - 4)); pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total); >> infile.close(); pw.close(); > > 
ID Number of Bags Total Cost 3005045 7 548.503245436 Error: Wrong Number of Bags 7543536 3 241.508684383 Error: Wrong Number of Bags 

You should not use i to save «number of bags». See the line i = infile.nextInt(); . Use another variable, then you should be fine. Also, you should keep reading until end of file, so you probably wouldn’t be able to write a for (int i = 0; i < n; i++) -style of loop.

There is no surprise that loop can iterates only one time. In each case you have break .

Also in this case you shouldn’t be using for loop, and especially not the way you are using it now. Just take a look at it, your loop would end only when this condition i >= 0 would be false, which means i would have to be negative, but even when i would become -1 like last number from your input it would still be incremented at the end of iteration thanks to i++ so you would end up with 0 >= 0 condition which is true, so loop would try to iterate again)

This way you will make sure that you will read int from file only when there will be next one to read. Just use your predefined bugs variable instead of i .

Another thing is that you are not including line separators in your printf formats. Add %n at the end of each one of them, and don’t use \t but specify space you want each number to hold like

How do you read a text file and print it to the console, The reason that java.io.BufferedReader@18fb397 is printed to the console is because you give the reference of the buffered reader as an argument to print, and not the string you want to print. BufferedReader r = new BufferedReader( new FileReader( «testing.txt» ) ); System.out.print(r);

Источник

Оцените статью