PrintWriter class in a separate method - java

Hello working on a small program that writes data to a file. I am using a if else statement for validation so I need the PrintWriter and FileWriter class/declaration in a separate method. I then call this method with the constructor of the main class. The problem I am having is when I moved the Printwriter class to it's own method I can no longer access it from my button click aciton l istener.
CODE:
private void OpenFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
PrintWriter outputFile = new PrintWriter(fw);
}catch(IOException error){
JOptionPane.showConfirmDialog(null, error);
}
}
When using outputFile. I get an error because it can't find outputFile. Why wont' this work?

define the PrintWriter as an instance variable in your main calss
not sure what are you trying to use this for
but make it public to get it working or don't use any modifier if you are working in the same class
so your code should be
public class MyClass
{
public PrintWriter outputFile;
.....
}
and then instantiate the instance when you get to the method
outputFile = new PrintWriter(fw);

First (by convention), Java method names start with a lower case letter. Second, you aren't returning the PrintWriter you're assigning it to a method local variable -
private PrintWriter openFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
return new PrintWriter(fw);
} catch(IOException error) {
JOptionPane.showConfirmDialog(null, error);
}
return null;
}
Alternatively, you could assign the PrintWriter to a class level variable,
private PrintWriter outputFile = null;
private void openFilePW(){
try{
String inputFileName = "addressBook.txt";
FileWriter fw = new FileWriter(inputFileName, true);
outputFile = new PrintWriter(fw);
} catch(IOException error) {
JOptionPane.showConfirmDialog(null, error);
}
}

Related

Java : How can I test save method?

I have a following save method, but I dont know how to verify that the method is working correctly. How can I verify it in Test Class ??
static void saveFile(List<String> contents, String path){
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
for(String data : contents){
pw.println(data);
}
}
Sorry, contents is not String, but List. But is there no need to make test class ?? because it is constructed by tested java method.
For testing, you may consider a test framework such as jUnit and write your test case. In your specific case, you could write something as follows:
public class TestCase {
#Test
public void test() throws IOException {
String contents = "the your content";
String path = "the your path";
// call teh metod
saveFile(contents, path);
// tacke a reference to the file
File file = new File(path);
// I assert that the file is not empty
Assert.assertTrue(file.length() > 0);
// I assert that the file content is the same of the contents variable
Assert.assertSame(Files.readLines(file, Charset.defaultCharset()).stream().reduce("", (s , s2) -> s+s2),contents);
}
static void saveFile(String contents, String path) throws IOException {
File file = new File(path);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(contents);
}
}
In this way, you have a framework to check if the your code works as you expect. If this isn't sufficient, you should look into a mock framework such as Mockito.
Remove FileWriter from you method like this
static void saveFile(List<String> contents, Writer writer){
PrintWriter pw = new PrintWriter(new BufferedWriter(writer));
for(String data : contents){
pw.println(data);
}
pw.flush();
}
In your JUnit test method use StringWriter for checking your saving logic
#Test
void testWriter() {
StringWriter writer = new StringWriter();
saveFile(Arrays.asList("test content", "test content2"), writer);
assertEquals("test content\ntest content2\n", writer.toString());
}
and in your real code
...
Writer writer = new FileWriter(new File(path));
saveFile(Arrays.asList("real content", "real content2"), writer);
...

How to create a txt file in Java?

I'm just want a program to register a user and then create a txt file to store there the information. I know it has to be with createNewFile method but I do not know how to use it. I'd try this in my code:
import java.util.*;
public class File{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
byte option=0;
do{
System.out.println("\nMENU:\n");
System.out.println("0.-EXIT");
System.out.println("1.-REGISTER USER");
System.out.println("\nPLEASE ENTER YOUR CHOICE:");
option = sc.nextByte();
}while(option!=0);
}//main
}//File
You can use a File object to create a new File an example is:
File createFile = new File("C:\\Users\\youruser\\desktop\\mynewfile.txt");
createFile.createNewFile();
If you want to read and write to the file you could use a PrintWriter or some other writing mechanism:
PrintWriter pw = new PrintWriter(createFile);
pw.write("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
If you need to append to the file you can do this:
PrintWriter pw = new PrintWriter(new FileOutputStream(createFile, true)); //true means append here
pw.append("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
// File file = new File("/users/your_user_name/filename.txt");// unix case
File file = new File("c:\\filename.txt"); //windows case
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Source: http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Ok so once you have the input from the user this is what you would use to write the username and password to a text file
try {
File file = new File("userInfo.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
//set to true so you can add multiple users(it will append (false will create a new one everytime))
output.write(username + "," + password);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
EDIT***
You can put all this in a method and call it every time you want to add the user
public void addUser(String username, String password){
//my code from above ^^
}

Why is is my program not pulling in the files from the folder

I have a program that is suppose to read all the files in my folder and combine the files into on file and place them into a new folder. Some of the files are not being pulled in and I do not know why.
The file names are wonder1.txt, wonder2.txt, wonder3.txt, and wonder4.txt and the folder name is Alice, but only a few of the files are actually in the new folder.
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.PrintWriter;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
File folder = new File("/Users/DAndre/Desktop/Alice");
//Reads in all the files in that folder
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "/Users/DAndre/Desktop/final/final_copy.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
The problem with your solution is that you haven't initialize PrintWriter in append mode, because of which the new file gets overwritten with the content of the last file that was written.
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\Shayan\\Desktop\\files2\\final_copy.txt";
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(newFileLocation), true /* append = true */));
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
The last argument in the constructor of FileOututStream is set to true, indicating that it should be opened in append mode.
You need to change
PrintWriter writer = new PrintWriter(newFileLocation);
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newFileLocation, true)))
Little explanation: append meant to write it additively, on the contrary write overrides the existing file. In your code you are creating a new file including one of your wonders, but on next iteration the file is recreated. So the content of previous wonder is gone.
With the change PrintWriter object is not recreating the file, instead it writes content to a BufferedWriter which also transfers the stream to an append able FileWriter object.
Little suggest: do not create a PrintWriter object on each iteration.
Second little suggest: You don't need PrintWriter. BufferedWriter itself is good enough as far as I see.

Error in File I/O

I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()

java write data to file without erasing the old content

how can i
write data to file without erasing the old content
Use new FileOutputStream(file, true). This will open file in "append" mode which will append all data written to the stream to the end of that file.
You mean "how do you append to a file"? Look for an [append-version of a constructor][1] of your File writing class, e.g.:
public FileWriter(String fileName,
boolean append)
throws IOException
Use this constructor and pass true for the append parameter.
[1]: http://download.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
if you used the new one in Java 7, you can use this way
try (BufferedWriter writer = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND))
in this code i use append (true) but my old date erase and new data overwrite on it please give me solution on it
public class FileOperation {
private static FileReader fileReader;
private static FileWriter fileWriter;
private static BufferedReader bufferedReader;
private static BufferedWriter bufferedWriter;
private static PrintWriter writer;
public static File file = new File("C:\\StudentInfo\\com\\education\\students\\file\\managing\\v1_0\\Student.txt");
public FileOperation() throws IOException {
fileReader = new FileReader(file);
fileWriter = new FileWriter(file, true);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
// FileOperation fo =new FileOperation();
}
public boolean enrollSudnents(ArrayList<Student> studentList) {
try {
writer = new PrintWriter(file);
writer.print("");
bufferedWriter = new BufferedWriter(new FileWriter(file));
for (Student s : studentList) {
String nameNumberString = String.valueOf(s.getRoll() + "!" + s.getFirstName() + "!" + s.getLastName()
+ "!" + s.getClassName() + "!" + s.getAddress() + "\n");
bufferedWriter.write(nameNumberString);
}
return true;
} catch (Exception e) {
return false;
} finally {
try {
bufferedWriter.close();
fileWriter.close();
} catch (Exception e) {
// logger.info("Exception Found In Adding data");
}
}
}

Categories

Resources