Printing to a file in java
Question: I am writing the length of the string into a file and the result is that value is being considered as ASCII value and the character specified with ASCII value is written in the file and then I try to read that character from with the help of FileInputStream and BufferInputStream and the result will not be displayed on the console. In our previous exercise, we learned that would find the text within the file «data.txt», but I am unsure about how to convert this into finding any file name inputted by the user. More details below.
Printing a Specified File Exercise Java
Taking a beginners course in Java and I am stuck on one of the exercises. We’re meant to print the text within a specific file, which we can find via the file’s name which was inputted by a user. In our previous exercise, we learned that
try(Scanner scanner = new Scanner(Paths.get("data.txt")))
would find the text within the file «data.txt», but I am unsure about how to convert this into finding any file name inputted by the user.
Exercise: Write a program that asks the user for a string, and then prints the contents of a file with a name matching the string provided. You may assume that the user provides a file name that the program can find.
The exercise template contains the files «data.txt» and «song.txt», which you may use when testing the functionality of your program. The output of the program can be seen below for when a user has entered the string «song.txt». The content that is printed comes from the file «song.txt». Naturally, the program should also work with other filenames, assuming the file can be found.
My code so far is:
import java.nio.file.Paths; import java.util.Scanner; public class PrintingASpecifiedFile < public static void main(String[] args) < Scanner scanner = new Scanner(System.in); System.out.println("Which file should have its contents printed?"); String fileName = scanner.nextLine(); //try(Scanner scanner = new Scanner(Paths.get(fileName))) < try(scanner = Paths.get(fileName)) < // this part of the code is underlined red while (scanner.hasNextLine())< String output = scanner.nextLine(); System.out.println(output); >> catch (Exception e) < System.out.println("Error: " + e.getMessage()); >> >
I have tried searching how to add a new scanner as that was a suggestion but every time I’ve tried it gets an error. Also the «try» section is underlined red and cannot seem to figure out why. The underlined red part says variables in try-with-resources are not supported in -source 8
If anyone has tips, I would really appreciate it! Thank you!
You used one Scanner for reading the file path from the console.
You need an other Scanner (or reader alternative) for reading the file.
try (Scanner fileScanner = new Scanner(fileName)) < try (Scanner fileScanner = new Scanner(Paths.get(fileName)))
Print from file after writing java, The method in the finally block reads the file and creates an ArrayList of objects and then stores it in an array of objects for printing
Java How to write to a text file
Java Print to File Example
Java Programming Tutorial - 80 - Writing to Files · Login and register from txt file using java Duration: 5:16
Writing and Appending to Text Files in Java | PrintWriter
In this video we will see how we can use a file writer and a print writer to write and append text
Duration: 8:13
How to print a PDF File using native JAVA (or open and print)
I created a invoice billing software using itextpdf 5. Is there any way to print the generated PDF using java?
The easiest way is using Desktop.print(File) .
Java - How to print to a file and the monitor at the same time?, Try using write() instead of print for(int x = 0; x
Problem in printing the content from the file
I am writing the length of the string into a file and the result is that value is being considered as ASCII value and the character specified with ASCII value is written in the file and then I try to read that character from with the help of FileInputStream and BufferInputStream and the result will not be displayed on the console. Why is the character from the file not printed to the console?
import java.io.*; class Fileoutput < public static void main(String args[]) < try < File f=new File("C:\\Users\\parsh\\YG2108\\Testfile.txt"); FileInputStream fins=new FileInputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt"); FileOutputStream fouts=new FileOutputStream("C:\\Users\\parsh\\YG2108\\Testfile.txt"); FileWriter bf=new FileWriter("C:\\Users\\parsh\\YG2108\\Testfile.txt"); BufferedInputStream fin=new BufferedInputStream(fins); BufferedOutputStream fout=new BufferedOutputStream(fouts); BufferedWriter bw=new BufferedWriter(bf); int i; String s1="Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc xdibnbnokcm knui9xkbmkl bv"; int length=s1.length(); //findin string length System.out.println(length); //printing length on console fout.write(length); //writting into the file System.out.println("Sucess"); while((i=fin.read())!=-1) < System.out.print((char)i); >bw.close(); fout.close(); fin.close(); bf.close(); fouts.close(); fins.close(); System.out.println("All done"); >catch(Exception e) > >
First See If The problem Is In The Way you Write inTo the File
Follow This Link How To Read from a file in Java and See This Link Also How to Write Into A File in Java Problem Is not in The Asci Because if the Length of the String is int (As it should be ) You Should Parse it using Integer.tostring(length_of_the_string) before you write it into the File
fout.write(Integer.toString(length));
You can Google for your Problem Before Asking on Stackoverflow ( It Might be Solved Before On Stackoverflow )
Your code is mixing reading with writing - you have both reading objects and writing objects opened at the same time. Since you are using BufferedOutputStream output is not written directly to file (when buffer is not full) and you are reading file before it contains any data.
So to solve it, flush the output stream with fout.flush(); before reading, or ideally separate reading from writing:
import java.io.*; class Fileoutput < public static void main(String args[]) throws IOException < File f = new File("test.txt"); f.createNewFile(); try (FileOutputStream fouts = new FileOutputStream(f); BufferedOutputStream fout = new BufferedOutputStream(fouts);) < String s1 = "Good Afternoon have a nice day frghunv9uhbzsmk zvidzknmbnuf ofbdbmkxm;jccipx nc xdibnbnokcm knui9xkbmkl bv"; int length = s1.length(); System.out.println(length); fout.write(length); //fout.flush(); //optional, everything is flushed when fout is closed System.out.println("Sucess"); >try (FileInputStream fins = new FileInputStream(f); BufferedInputStream fin = new BufferedInputStream(fins);) < int i; while ((i = fin.read()) != -1) < System.out.print((char) i); >System.out.println("All done"); > > >
Java Program to Read Content From One File and Write it into, The program prints the content in that file, and then in the next line, it will print File reading and writing done(if there is no error
Print Contents of Text File to Screen in Java
- Scanner Class in Java
- BufferedReader Class in Java
- 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);
- To begin, you have to import the library java.io* .
- 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.
- FileReader ( File file) - creates a new FileReader from the specified File .
- FileReader ( FileDescriptor fdt) - Given the FileDescriptor to read from, creates a new FileReader .
- 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
Reading and printing a text file in Java
I am trying to read lines from a text file in Java, but there is a lot going on. Is this the best way to do this? I am especially concerned with resource leaks.
import java.io.*; public class Filing < public static void main(String[] args) throws FileNotFoundException, IOException < FileReader fr = new FileReader("/Users/thomaspovinelli/Desktop/apps.txt"); BufferedReader br = new BufferedReader(fr); String buffer; String fulltext=""; while ((buffer = br.readLine()) != null) < System.out.println(buffer); fulltext += buffer; >br.close(); fr.close(); > >
3 Answers 3
Never import the full package. It is considered bad practice to do so. Instead, import what you need and only what you need.
Instead of just reading a file then printing it, why don't you create a method that reads all line of a file and returns a list of all the lines? This way, you can do more with the result:
public static List getAllLines(File file) throws FileNotFoundException, IOException < FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String buffer; String fulltext=""; while ((buffer = br.readLine()) != null) < System.out.println(buffer); fulltext += buffer; >br.close(); fr.close(); >
I am especially concerned with resource leaks.
Since Java 7, there is such thing as a try-with-resources statement, which automatically closes the reader when an exception occurs, which you are not doing here. Your current code has memory leaks!
With some other improvements:
public static List readAllLines(File file) < Listresult = new LinkedList<>(); try (BufferedReader reader = new BufferedReader(new FileReader(file))) < for (String current = reader.readLine(); current != null; current = reader .readLine()) < result.add(current); >> catch (IOException e) < e.printStackTrace(); >return result; >
By the way, this is actually the code I use often to read all lines of a file.
\$\begingroup\$ It would be safer to construct BufferedReader and FileReader separately rather than as a chain, in case the FileReader constructor succeeds but the BufferedReader constructor fails. \$\endgroup\$
\$\begingroup\$ If you want a public static List
Not sure about the best way, but I'd personally favor one of the options using java.nio and java.util.stream:
public static List readAllLines(String fileName) < Listresult = new ArrayList<>(); try < result.addAll(Files.readAllLines(Paths.get(fileName))); >catch (IOException e) < e.printStackTrace(); >return result; >
public static List readAllLines(String fileName) < Listresult = new ArrayList<>(); try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) < br.lines().forEachOrdered(result::add); >catch (IOException e) < e.printStackTrace(); >return result; >
And if for some reason you cannot use either of those, you might want to have a look at FileUtils#readLines(java.io.File) from Apache Commons IO (although it's probably not worth adding that dependency only for this task).
In general, if you are concerned about (potential) resource leaks and you are using Eclipse, I advise to go to Window > Preferences > Java > Compiler > Errors/Warnings and set the severity level of "Resource leak" and "Potential resource leak" to at least "Warning". This way your IDE will tell you where you need to be careful.
\$\begingroup\$ I think using ArrayList in lieu of LinkedList should be good enough. 🙂 \$\endgroup\$
FileNotFoundException is a kind of IOException , so you only need to declare throws IOException .
A cleaner way of ensuring that your resources get closed is to use try-with-resources. Write it as fr = … and br = … instead of br = new BufferedReader(new FileReader(…)) to ensure that each resource gets closed, even if the FileReader constructor succeeds but the BufferedReader constructor fails.
try (FileReader fr = new FileReader(…); BufferedReader br = new BufferedReader(fr)) < StringBuilder fullText = new StringBuilder(); for (String line; (line = br.readLine()) != null; fullText.append(line)) < System.out.println(line); >>
Repeated string concatenation ( fulltext += buffer ) is O(n 2 ): each time you end up re-copying all of fulltext all over again. Use a StringBuilder instead. But in this program, you don't need to, since you never even use fulltext . (By the way, your fulltext is probably not what you want: it has all of the line terminators stripped out, since that's what BufferedReader.readLine() does.)
There's nothing really line-oriented about your program, so there is little reason to scan for line breaks. The simplest way to achieve the same results is using java.nio.file.* :
Files.copy(Paths.get(…), System.out);