Java Read / Write To File - BufferedReader BufferedWriter [duplicate] - java

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}

public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );

You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}

Related

Append text to file and print it's contents to console simultaneously?

I've spent over an hour on this, and i just can't get any text to show up in the .txt file. What am i doing wrong?
import java.util.*;
import java.io.*;
public class writer {
public static void main(String[] args) {
try {
File txt = new File("myTextFile.txt");
FileWriter fw = null;
fw = new FileWriter(txt);
BufferedWriter edit = null;
edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
Scanner sc = new Scanner(txt);
while (sc.hasNextLine()) {
String i = sc.nextLine();
System.out.println(i);
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit: Added a .write, but it's still not working
You never close the BufferedWriter instance and you never flush it either. So you never leave a change the buffer of the stream to be effectively written in the physical file.
Actually you read the file from the same source that you use just before to write in. So you have to explicitly flush the buffer of BufferedWriter before reading the content with the Scanner :
BufferedWriter edit = new BufferedWriter(fw);
String s = "more text", line = null;
edit.write(s);
edit.flush(); // modification here
Scanner sc = new Scanner(txt);

Java IO: Using scanner and printWriter to copy the contents of a text file and put them in another text file

Alright so I have a very small program I'm working on designed to take the contents of a text file, test.txt, and put them in another empty file testCopied.txt . The trick is that I want to use Scanner and printWriter as I am trying to understand these a bit better.
Here is what my code looks like:
import java.io.*;
import java.util.*;
public class CopyA
{
public static void main(String [] args)
{
String Input_filename = args[0];
String Output_filename = args[1];
char r = args[2].charAt(0);
try
{
Scanner sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
PrintWriter printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine();
printer.write(s);
}
sc.close();
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
}
This compiles, but when I look at testCopied.txt it is still blank, and hasn't had test.txt's content transferred to it. What am I doing wrong? Java IO is pretty confusing to me, so I'm trying to get a better grasp on it. Any help is really appreciated!
You have missed out flush() and close() for the PrintWriter object which you need to add
and then use the line separator using System.getProperty("line.separator") while writing each line into second file.
You can refer the below code:
PrintWriter printer = null;
Scanner sc = null;
try
{
String lineSeparator = System.getProperty("line.separator");
sc = new Scanner(new File(Input_filename));
FileWriter fw = new FileWriter(Output_filename);
printer = new PrintWriter(fw);
while(sc.hasNextLine())
{
String s = sc.nextLine()+lineSeparator; //Add line separator
printer.write(s);
}
}
catch(IOException ioe)
{
System.out.println(ioe);
} finally {
if(sc != null) {
sc.close();
}
if(printer != null) {
printer.flush();
printer.close();
}
}
Also, ensure that you are always closing resources in the finally block (which you have missed out for Scanner object in your code).

Java Program read input from a text file and modify it accordingly

I am writing a Java program that inputs a test file, performs some modifications to the data, then writes it to a new file output.
The input text file looks like this...
url = http://184.154.145.114:8013/wlraac name = wlr samplerate = 44100 channels =2 format = S16le~
url = http://newstalk.fmstreams.com:8080 name = newstalk samplerate = 22050 channels = 1 format = S16le
The program needs to be able to change the samplerate to 44100, and the channels to 1, if they don't already have these values. I would also remove the url and name pieces completely. After these changes, the new line needs to be written out to a different output text file.
So far, all my program can do is select a file and display the contents of the file to the user. Could someone please point me in the right direction for how my program should work
to achieve my required outcome.
As somebody asked here is what I have so far
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class reader2 {
public reader2() {
}
public static void main(String[] args) {
reader(args);
}
public static void reader(String[] args) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt")
|| f.isDirectory();
}
public String getDescription() {
return "Text Documents (.txt)";
}
});
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getName();
String pathToFIle = chooser.getSelectedFile().getPath();
System.out.println(name);
try{
BufferedReader reader = new BufferedReader( new FileReader( pathToFIle ) ); //Setup the reader
while (reader.ready()) { //While there are content left to read
String line = reader.readLine(); //Read the next line from the file
String[] tokens = line.split( "url = " ); //Split the string at every # character. Place the results in an array.
for (String token : tokens){ //Iterate through all of the found results
//System.out.println(token);
System.out.println(token);
}
}
reader.close(); //Stop using the resource
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
You will need to do something like this ...
Read the contents of the file, one line at a time
Split the line up into the individual components, such as splitting it on the 'space' character
Change the sample rate and channel values according to your question
Write the line out to a file, and start again from step 1.
If you give this a try, post some code on StackExchange with any problems and we'll try to assist.
can you try
File file = new File( fileName );
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
String line = br.readLine();
String newLine = line.replaceAll( "samplerate =\\s*\\d+", "samplerate = 44100");
newLine = newLine.replaceAll( "channels =\\s*\\d+", "channels = 1");
fw.write(newLine + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
Ref: Files java replacing characters

Address book program with more functionality

I've done a small address book program that allows the user to:
add contact
search contact
delete contact
display all contacts
It ends after you enter one option, I want it to keep running until the user says eg 5- exit
another problem I want the data to written and read to data.dat file
I'm completly new, can some tell me how to split up this into separate classes and inherit each other.
my code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class AddressBookOperations
{
public static void main(String[] args) throws IOException
{
String s = null;
String s2 = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// Console in = System.console();
System.out.println(" Please select the required operations.\n"
+ " 1- Add contact\t 2- search contact\t 3- delete contact\t 4- display all contacts\n");
s2 = in.readLine();
if (s2 != null && !(s2.equals("1") || s2.equals("2") || s2.equals("3") || s2.equals("4")))
{
System.out.println("Invalid Operation Selected\n");
System.exit(0);
}
else
{
s = s2;
}
if (s != null)
{
String dataLine;
String data;
if (s.equals("1")) {
System.out.println("Name: ");
dataLine = in.readLine();
data = dataLine;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("PhoneNumber: ");
dataLine = in.readLine();
data = data + ":" + dataLine;
writeToFile("C:/AddressBook.bat", data, true, true);
} else if (s.equals("2")) {
System.out.println("Enter Name 0r PhoneNumber: ");
dataLine = in.readLine();
String result = readFromFile("C:/AddressBook.bat", dataLine);
System.out.println("Search Results\n" + result);
} else if (s.equals("3")) {
System.out.println("Enter Name: ");
dataLine = in.readLine();
data = dataLine;
System.out.println("PhoneNumber: ");
dataLine = in.readLine();
data = data + ":" + dataLine;
deleteFromFile("C:/AddressBook.bat", data);
} else if (s.equals("4")) {
String result = readFromFile("C:/AddressBook.bat", null);
System.out.println("Search Results\n" + result);
}
}
}
private static void deleteFromFile(String string, String dataLine) {
String data = readFromFile(string, null);
data = data.replaceAll(dataLine, "");
writeToFile(string, data, false, false);
}
public static boolean writeToFile(String fileName, String dataLine,
boolean isAppendMode, boolean isNewLine) {
if (isNewLine) {
dataLine = "\n" + dataLine;
}
try {
File outFile = new File(fileName);
DataOutputStream dos;
if (isAppendMode) {
dos = new DataOutputStream(new FileOutputStream(fileName, true));
} else {
dos = new DataOutputStream(new FileOutputStream(outFile));
}
dos.writeBytes(dataLine);
dos.close();
} catch (FileNotFoundException ex) {
return (false);
} catch (IOException ex) {
return (false);
}
return (true);
}
/*
* Reads data from a given file
*/
public static String readFromFile(String fileName, String dataLine2) {
String DataLine = "";
String fileData = "";
try {
File inFile = new File(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(inFile)));
if (dataLine2 != null)
{
while ((DataLine = br.readLine()) != null)
{
if (DataLine.contains(dataLine2)) {
fileData = DataLine;
}
}
}
else
{
while ((DataLine = br.readLine()) != null)
{
fileData = fileData + "\n" + DataLine;
//System.out.println(DataLine);
}
}
br.close();
}
catch (FileNotFoundException ex)
{
return (null);
} catch (IOException ex)
{
return (null);
}
return (fileData);
}
public static boolean isFileExists(String fileName) {
File file = new File(fileName);
return file.exists();
}
}
You can wrap your logic in a while loop which terminates when a given boolean is true, therefore you will keep going back to the start after each operation is performed. For example:
boolean isRunning = true;
while (isRunning) {
//your code here
if (s2.equals("5")) {
isRunning = false;
}
}
You should also move all of your logic out of main() and into its own seperate function that is called from main(). I'm also not sure why you are writing to a .bat file? Change the extension to .dat if you want to write to a .dat file.
I guess you just want a general code review. Here are my thoughts:
1. Scanner is much easier to use for console input because you can specify input types, such as nextInt(). To initialize it, just use
Scanner sc = new Scanner(System.in);
You can use the same Scanner for every user input in the course of the program. Also, remember to call Scanner.close() before your program exits.
2. Initialize your BufferedReader as follows:
// file is a String variable
BufferedReader in = new BufferedReader(new FileReader(file));
Analogously, read files as follows:
BufferedWriter br = new BufferedWriter(new BufferedReader(file));
3. To keep the program running, practice implementing a do-while block:
boolean quit = false;
do {
// loop program; when user is finished, set quit = true
} while (!quit)
4. For the conditionals based on "Please select the required operations", practice implementing a switch block.
5. Separate the logic for parsing the user input and the logic for operating on the address book by making the console interface a separate class, say, AddressBookUI. When it is runs, it should immediately create an instance of the AddressBookOperations class, and call appropriate methods from there based on user input - AddressBookOperations should have a separate method for each operation (this will also make your switch quite short). It should also have the following private (but not static) variables to store the filename and BufferedRead/Writer. The class should have a constructor with an String filename argument which initializes these variables.
6. Deleting specific lines in files is rather tricky in Java. Try this:
Create a BufferedReader for the file.
Create a new temporary file, and create a BufferedWriter for it.
Read the file line by line. For each line, if it is not the line you want to delete, write it to the temporary file.
Close the reader and the writer
Delete the old file
Rename the temp file to the filename.

Reading and displaying data from a .txt file

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Categories

Resources