I am working on a few lessons in Java, and the instructor started introducing how IO working in Java. I just have a couple of question that an experience Java programmer could clarify.
The piece of code below is a program that creates a (notepad) text file in the same file directory I am writing my code. After that, it simply prints basic lines of text to that file.
import java.io.FileWriter; //Imports Filewriter class
import java.io.PrintWriter; //Imports PrintWriter class
import java.io.IOException; //Imports IOException
public class Chap17Part2
{
public static void main(String[] args) throws IOException
{
String fileName = "grades.txt"; //Creating name for file
PrintWriter outFile = new PrintWriter(new FileWriter(fileName)); //Question 1
outFile.println(85); //Prints to file
outFile.println(77); //Prints to file
outFile.close(); //Ends buffer, and flushes data to file.
}
}
Question 1: Due to only brief explanations by the instructor, this line of code is a bit confusing to me. I know that in this line, we are creating the "outFile" object. After that, we are calling the PrintWriter constructor, and inside its parameters, we are calling the constructor for FileWriter. Inside of its constructor, we are calling the name of the file we created as a String. That is the confusing part. I'm not understanding exactly what PrintWriter, and FileWriter are doing. It looks like FileWriter is creating our file, and PrintWriter is giving us the println() method to print the two numbers to the file. After doing research, I have found that you can pretty much achieve the same purpose with both FileWriter, and PrintWriter. What is the purpose for teaching file processing in this manner, and what exactly are the two classes doing? Thank you for the help in clarifying this for me!
The code is equivalent to
FileWriter fw = new FileWriter(fileName);
PrintWriter outFile = new PrintWriter(fw);
So it first creates a FileWriter, which writes characters to a file, and then creates a PrintWriter which prints its values to the FileWriter.
Related
Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());
Im building a Car Rental program and what I want it to, for now, is:
Register a user
Register a car
using .txt files to store the data.
With the code I've written, I can register only a single car and user. Every time I run the register method for client or car, the last register is erased.
Can you help me with this? Also, later I'm going to implement a way to rent a car, but I don't know how to do that also, so if you have any ideas of how to do it, please tell me!
Also I intend to do it without SQL or such things.
This is the code I'm using to register a user (I'm using netbeans with JForm):
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String nomeClient = txtNomeClient.getText();
String idClient = txtIdClient.getText();
File file = new File("clients.txt");
try {
PrintWriter output = new PrintWriter(file);
output.println(nomeClient);
output.println(idClient);
output.close();
JOptionPane.showMessageDialog(null, "Client registed!");
} catch (FileNotFoundException e) {
}
}
The problem is that you overwrite the existing file clients.txt, instead of appending to it by calling new PrintWriter(file). You can use the following code:
FileWriter fileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(fileWriter));
This way, you append the end of the file, see the constructor FileWriter(File file, boolean append). The documentation describes it perfectly:
Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
The FileWriter is just used to open a file in append mode, as PrintWriter does not have a suitable constructor to do that directly. You could also write characters with it, but a PrintWriter allows for formatted output. From the documentation of FileWriter:
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
The PrintWriter uses the FileWriter passed in its constructor to append to the destination file, see here for a good explanation. As stated there, you could also use an FileOutputStream. There are multiple ways to do this.
Here is an example using a FileOutputStream and a BufferedWriter, which supports buffering and can reduce unnecessary writes that penalize performance.
FileOutputStream fileOutputStream = new FileOutputStream("clients.txt", true);
BufferedWriter bufferedWriter = new BufferedWriter(fileOutputStream);
PrintWriter printWriter = new PrintWriter(bufferedWriter);
I have this text file of the format:
Token:A1
sometext
Token:A2
sometext
Token:A3
I want to split this file into multiple files, such that
File 1 contains
A1
sometext
File 2 contains
A2
sometext
I do not have much idea about any programming or scripting language as such, what would be the best way to go about the process? I was thinking of using Java to solve the problem.
if you want to use java, I would look into using Scanner in conjunction with File and PrintWriter with a for loop and some exception handling you will be good to go.
import the proper libraries!
import java.io.*;
import java.util.*;
declare the class of course
public class someClass{
public static void main(String [] args){
now here's where stuff starts to get interesting. We use the class File to create a new file that has the name of the file to be read passed as a parameter. You can put whatever you want there whether its a path to the file or just the file name if its in the same directory as your code.
File currentFile = new File("new.txt");
if (currentFile.exists() && currentFile.canRead()){
try{
next we create a scanner to scan through that newly created File object. the for loop continues on as long as the file has new tokens to scan through. .hasNext() returns true only if the input in the scanner has another token. PrintWriter writes and creates the files. I have it set that it will create the files based on the iteration of the loop (0,1,2,3 etc) but that can be easily changed. (see new PrintWriter(i + ".txt". UTF-8); )
Scanner textContents = new Scanner(currentFile);
for(int i = 0; textContents.hasNext(); i++){
PrintWriter writer = new PrintWriter(i + ".txt", "UTF-8");
writer.println(textContents.next());
writer.close();
}
these catch statements are super important! Your code wont even compile without them. If there is an error they will make sure your code doesn't crash. I left the inside of them empty so you can do what you see fit.
} catch (FileNotFoundException e) {
// do something
}
catch (UnsupportedEncodingException i){
//do something
}
}
}
}
and thats pretty much it! if you have any questions be sure to comment!
There is no best way and it depends on your environment and need actually. But for any language figure out your basic algorithm and try using the best available data structure(s). If you are using Java, consider using guava splitter and do look into its implementation.
I want to output my result to a file. I use BufferWriter as below:
public class class1{
...
void print()
{
System.out.println("The name "+outName()+" Tel: "+outNumber());
try{
PrintWriter printWriter=new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
printWriter.println("The name "+outName()+" Tel: "+outNumber());
}catch (IOException e){}
}
}
However I have another class and main function also having their own print functions
public class class2{
...
void print()
{
System.out.println("The name "+outName()+" Tel: "+outNumber());
try{
PrintWriter printWriter=new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
printWriter.println("The name "+outName()+" Tel: "+outNumber());
}catch (IOException e){}
}
}
public static void main(String[] args) throws IOException{
try{
PrintWriter printWriter=new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
...
printWriter.println("something");
printWriter.close();
}catch(IOException e){ }
}
The code pass the compilation, but only the output from the main function appear in the output file. How to fix it please?
There are three (OK ... make that four, no five) significant problems with your code.
In class2 you don't close or flushthePrintWriter` after you have finished writing. That means that the data will never be written out to the file. That's why you never see the output.
This is the obvious bug. But the rest of the problems are also important. Arguably MUCH MORE important ... so keep reading.
The print() method in class2 leaks file descriptors (!). Each time you call it, it will open a file descriptor, write stuff ... and drop it on the floor. If you call print() repeatedly, the FileWriter constructor will fail. You need to close the file, and the cleanest way to ensure it always happens is to write the code like this:
try (PrintWriter printWriter =
new PrintWriter(new BufferedWriter(
new FileWriter("myfile.txt", true)))) {
printWriter.println(...);
}
This is a "try with resource" ... and it guarantees that the resource (printWriter) will be closed when the scope exits.
You are squashing exceptions.
try {
PrintWriter printWriter - ...
} catch (IOException e) {
// SQUASH!!!
}
This is really, really bad. Basically, you have written your code to ignore the exception. Pretend it never happened ... and throw away the information in the exception that would say why it happened.
You should only ever squash an exception if you are absolutely sure that you will only catch expected exceptions, and that ignoring them is absolutely correct. Here, it isn't. If an IOException is thrown here, you need to know why!
Opening multiple streams to write to the same file is a recipe for problems. The streams won't be synchronized, and you are likely to see the output interleaved in the output file in unexpected ways. If the output pipelines include buffering (like yours do), the problem is worse.
You have serious Java style issues:
A class name should always start with an uppercase letter. Always. Even in example code snippets ...
Code should be consistently indented. I recommend using SP characters rather than TAB characters because tabs don't display consistently.
There are style rules about where you should and should not put spaces and line breaks. For example, there should always be whitespace around a binary operator. Find a Java style guide, read it and format your code accordingly.
Always write your code so that >>other people<< can read it.
I think you need to call new class1().print() or new class2().print(), i.e. you need to instantiate the instances first.
Also please remember to close the file in each print() function.
It's because you're never closing anything exept in main(). You're also swallowing exceptions, so you're concealing the truth from yourself. Don't do that.
But it's poor practice. You should keep the file open and use the same FileWriter, BufferedWriter, PrintWriter, and synchronize access to them so you don't get interleaved data.
Not a good idea overall.
OK, I'm having some trouble writing multiple lines to a text file.
the program runs, but it won't use new lines each time
when I want it run 4 times, the text file should look like:
a
b
c
d
instead, it looks like:
d
who knows how to fix this problem? all imports are correctly imported.
source(it's been slightly edited, assume everything is properly defined):
import java.io.*;
public class Compiler {
public static void main (String args[]) throws IOException
{
//there's lots of code here
BufferedWriter outStream= new BufferedWriter(new FileWriter("output.txt"));
outStream.newLine();
outStream.write(output);
outStream.close();
}
}
Make sure that when you create an instance of a FileWriter, that you are appending to the end of it. This can be done by using this specific FileWriter constructor which takes an additional boolean as a second parameter. This boolean tells the FileWriter to append to the end of the file, rather than overwriting the file.
BufferedWriter outStream= new BufferedWriter(new FileWriter("encoded.txt", true));
By default FileWriter will overwrite the file. What you might want to do is define the reader in the following manner:
new FileWriter("encoded.txt", true)
This way the file will be appended to instead of being overwritten.
Hope this helps!
I'm not sure what this code is supposed to do. It throws an error if your input string is more than one character long, because you close your FileWriter inside the loop, then try to write to it again.
I'm interpreting your question the following way: you're wondering why only the most recent output is in the file. In that case, it's because you didn't create your FileWriter in append mode. Look at the different constructors available for FileWriter, and use the one that allows you to append to the file.