System.out.println prints the string but System.out.print does not - java

I am trying to store the words in a file separated by coma in a java array
The file is
Age,Income,Student,Credit Rating,Class: Buys Computer
Youth,high,No,Fair,No
Youth,high,No,Excellent,No
Middle aged,high,No,Excellent,No
Senior,medium,No,Fair,Yes
Senior,Low,Yes,Fair,Yes
Senior,Low,Yes,Excellent,No
public class Test {
public static void main(String args[]) throws FileNotFoundException, IOException{
FileInputStream f=new FileInputStream("F:\\pr\\src\\dmexam\\inp2.txt");
int size,nr=7,nc=5,j=0,i=0;
char ch;
String table[][]=new String[nr][nc];
size=f.available();
table[0][0]=new String();
while(size--!=0){
ch=(char)f.read();
if(ch=='\n')
{
i++;
if(i>=nr)
break;
table[i][0]=new String();
j=0;
continue;
}
if(ch==',')
{
j++;
table[i][j]=new String();
continue;
}
table[i][j]+=ch;
}
f.close();
System.out.println("The given table is:::---");
for(i=0;i<nr;i++){
for(j=0;j<nc;j++){
System.out.print(" "+table[i][j]);
System.out.print(" ");
}
}
}
}
But the output is
The given table is:::---
But if the for is changed like this
System.out.println("The given table is:::---");
for(i=0;i<nr;i++){
for(j=0;j<nc-1;j++){
System.out.print(" "+table[i][j]);
System.out.print(" ");
}
System.out.println(table[i][nc-1]);
}
The output is
The given table is:::---
Age Income Student Credit Rating Class: Buys Computer
Youth high No Fair No
Youth high No Excellent No
Middle aged high No Excellent No
Senior medium No Fair Yes
Senior Low Yes Fair Yes
Senior Low Yes Excellent No
I want to know "why System.out.print is not workig???"...

The PrintStream that System.out uses has an internal buffer, since writing to stdout is relatively expensive -- you wouldn't necessarily want to do it for each character. That buffer is automatically flushed when you write a newline, which is why println causes the text to appear. Without that newline, your string just sits in the buffer, waiting to get flushed.
You can force a manual flush by invoking System.out.flush().

Okay let me try to help you out here. So you are making your life really rough at the moment. Have you tried to look at different libraries like BufferedWritter/FileWritter?
You can easily import these into your project using:
import java.io.BufferedWritter;
import java.io.FileWritter;
It is also recommended to catch errors using the IOException library:
import java.io.IOException;
As for the separation of the words, these libraries give you tools like control over the delimiter. For example we can do something like this:
//this is if you are creating a new file, if not, you want true to append to an existing file
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt", boolean false));
try
{
// write the text string to the file
bw.write("Youth,high,No,Fair,No");
// creates a newline in the file
bw.newLine();
}
// handle exceptions
catch (IOException exc)
{
exc.printStackTrace();
}
// remember to close the file at the end
bw.close();
Now that is for hard coding the data, but we can do this with a for loop. We can add delimiters in the function within the for loop, for example: (I am not sure how you have the data stored, but I am assuming you save it in an array. I am also assuming there will ALWAYS be 5 sets of data per line)
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt", boolean false));
for (int i = 1, i <= listName.size()+1, i++) {
if (i % 5 == 0) {
bw.write(listName.get(i-1));
bw.write(", ");
bw.newLine();
} else {
bw.write(listName.get(i-1));
bw.write(", ");
}
}
This would write to the file:
Youth,high,No,Fair,No
Youth,high,No,Excellent,No
Middle aged,high,No,Excellent,No
Senior,medium,No,Fair,Yes
Senior,Low,Yes,Fair,Yes
Senior,Low,Yes,Excellent,No
This may make your life a little easier (if I am understanding your needs clearly). Next time please make sure to flesh out your question more than you did.
DISCLAIMER: I did not test all of the code, so if you find an error please let me know and I will edit it as needed. If I get time I will make sure it works.

Related

To print console output to text file Java?

I'm trying to send the output of my program to a text file called results.txt . Here's my attempt
public void writeFile(){
try{
PrintStream r = new PrintStream(new File("Results.txt"));
PrintStream console = System.out;
System.setOut(r);
} catch (FileNotFoundException e){
System.out.println("Cannot write to file");
}
But everytime I run the code and open the file the file is blank. This is what i want to output:
public void characterCount (){
int l = all.length();
int c,i;
char ch,cs;
for (cs = 'a';cs <='z';cs++){
c = 0;
for (i = 0; i < l; i++){
ch = all.charAt(i);
if (cs == ch){
c++;
}
}
if (c!=0){
//THIS LINE IS WHAT I'M TRYING TO PRINT
System.out.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
}
}
}
Where am I going wrong that it keeps creating the file but not writing to it?
(Btw i do have a main method)
use:
PrintWriter writer = new PrintWriter("Results.txt");
writer.print("something something");
don't forget to add:
writer.close();
when you are done!
As you found, System.out IS-A PrintStream and you can create a PrintStream, passing it a File to have it write to that file. This is the beauty of polymorphism --- your code writes to a PrintStream and it doesn't matter what kind it is: console, file, even network connection, or zipped encypted network file.
So instead of messing with System.setOut (usually a bad idea, as it may have unintended side effects; do this only if you absolutely have to (e.g., in some tests)), just pass the PrintStream of your choice to your code:
public void characterCount (PrintStream writeTo) {
// (your code goes here)
writeTo.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
// (rest of your code)
}
Then you call your method as you want:
public static void main(String[] args) throws FileNotFoundException {
new YourClass().characterCount(System.out);
new YourClass().characterCount(new PrintStream(new File("Results.txt")));
}
(Note that I declared that main may throw a FileNotFoundException, as new File("...") can throw that. When that happens, the program will exit with an error message and stack trace. You could also handle it like you did before in writeFile.)
JAVADOC: "A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently."
PrintStream can be used to write to an OutputStream, not directly to a file. So you can use PrintStream to write to a FileOutputStream and then write to the file with that.
If you just want to simply write to a file though, you can use Cans answer easily!

Why does the buffered writer does not write immediately when the write() method is called

package javaapplication11;
import java.util.Scanner;
import java.io.*;
/**
*
* #author jenison-3631
*/
public class JavaApplication11 {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException
{
// TODO code application logic here
// File file = new File("/Users/jenison-3631/Desktop/csvv.txt");
int n,z=1;
FileWriter writr = new FileWriter("/Users/jenison-3631/Desktop/csvv.txt");
FileReader fr= new FileReader("/Users/jenison-3631/Desktop/csvv.txt");
BufferedReader br=new BufferedReader(fr);
BufferedWriter bw= new BufferedWriter(writr);
try{
while(z==1)
{
System.out.println("please enter your choice\n1.Add number\n2.Delete number\n3.List all\n4.Search number");
Scanner s= new Scanner(System.in);
n= s.nextInt();
switch(n)
{
case 1:
String str;
String number;
System.out.println("Enter the name");
s.nextLine();
str= s.nextLine();
System.out.println("Enter the number");
number=s.nextLine();
System.out.println(str+" "+number);
/* writer.append(str);
writer.append(',');
writer.append(number);
writer.append('\n');*/
String actual=str+","+number+"\n";
bw.write(actual,0,actual.length());
break;
case 2:
String del=null;
String line=null;
String spl=",";
System.out.println("Enter the name whose phone number should be deleted");
s.nextLine();
del=s.nextLine();
while((line=br.readLine())!=null)
{
String[] country = line.split(spl);
System.out.println("hai"+country[0]);
}
System.out.println(del);
break;
}
System.out.println("Do u wish to continue....if yes press 1 else press 2");
z= s.nextInt();
}
}
finally{
bw.close();
br.close();
}
}
}
in my case 2 when I try to bring back the name from the file csvv.txt it is not working because the file is actually without data. But when I run the case 1 alone the data is writtern in the file
BufferedWriter does not write immediately write because it buffers the data it is given.
Imagine you work in the mail room at your company. Somebody walks in with a letter to send to a client. It takes you 10 minutes to go down to the post office down the street to mail it. Do you take the letter immediately, or would you wait to see if anybody else is going to bring you a letter first?
This is buffering: instead of doing an expensive operation (walking down the street) immediately, you can wait and gather lots of things to do at once - if you have 100 letters to mail, it will still take you just 10 minutes to walk down the street, even if it takes you marginally longer to stuff them in the mail box.
It's the same with IO on a computer: it's expensive. Writing to disk, sending to the network etc are slow, so you don't want to do them repeatedly if you don't have to.
But should you care that buffering is taking place? Largely, no. In the mail room example, people just want to drop off their letters, and know it will be delivered at some point in the future. And once they've dropped it off, it doesn't matter to them whether you run down the street now or wait for 100 letters first.
In code, you often don't care when the data gets written. It just gets written at some point, e.g. when the file writer is closed, or once you've asked to write a certain amount of data to the file.
If you care about the data being written before one of these things happen, you can call bw.flush() to force it to happen immediately.
You can read more about IO and buffering in Oracle's Essential Java tutorial. You can start here, but the bit about buffering is here

Writing to files and I/O

I'm trying to write a program that gets a users input that is then written to an output file called userStrings.txt. I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Here is my code:
import java.io.*;
import java.util.Scanner;
public class Murray_A04Q2 {
public static void main(String[] args) throws IOException {
// Name of the file
String fileName = "userStrings.txt";
Scanner scan = new Scanner(System.in);
try {
// FileReader reading the text files in the default encoding.
FileWriter fileWriter = new FileWriter("userStrings.txt");
// Wrapping FileReader in BufferedReader.
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("A string");
bufferedWriter.write("Another string");
bufferedWriter.write("Yet more text...");
System.out.println("Enter something, DONE to quit: ");
String input = scan.nextLine();
// Closing file
bufferedWriter.close();
}
catch (IOException ex){
System.out.println("Error writing to file " + "userStrings.txt" + "");
}
} // End of method header
} // End of class header
In order to write to a file, do I still use System.out.println? and is the bufferedWriter.write even necessary? I'm just trying to understand the I/O and writing to files better.
Thanks!
In order to write to a file, do I still use System.out.println?
No. That writes to standard output, not to your file.
If you are using println then you need to wrap your BufferedWriter with a PrintWriter. (Look at the javadocs for the System class where the out field is documented.)
and is the bufferedWriter.write even necessary?
If you are going to write directly to the BufferedWriter then yes, it is necessary, though you probably need to an appropriate "end of line" sequence. And that's where it gets a bit messy because different platforms have different native "end of line" sequences. (If you use PrintWriter, the println method picks the right one to use for the execution platform.)
I'm also trying to stop the processing once the user inputs 'done', but I'm not sure how to accomplish this.
Hint: read about the Scanner class and System.in.
Right under you take input from the console, run a while loop to test that input is not equal to "done". Inside the while loop, add input to your file and get the next line of input.
while(!input.toLowerCase().Equals("done"))
{
bufferedWriter.write(input);
input = scan.nextLine();
}

text file to console directly

Was thinking of making a program,such that whatsoever I write on a text file ,it should come on the console
made this program
import java.io.*;
class Redirector
{
public static void main(String[] args) {
try
{
if(args.length!=1)
{
throw(new Exception("wrong way"));
}
System.setIn(new FileInputStream("b.txt"));
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
PrintStream x=new PrintStream(new FileOutputStream(args[0]));
System.out.println("enter text,end to terminanate");
while(true)
{
String str=r.readLine();
if(!str.equalsIgnoreCase("end"))
System.out.println(str);
else
break;
}
System.out.println("done");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
but the problem is that I want the whatsoever I write dynamically on the file and press enter should come on the console,whereas in this case it should be saved
What you're asking for is not possible. As long as you don't save the text file, its contents are not actually on the disk, they're only in memory.
You could theoretically try to access it in the allocated memory of whatever program you're using to edit the text file, but this is very difficult as it would require knowing the layout of its memory chunk. Moreover, it is a huge security risk, so most modern operating systems will make very sure you can't do it.

How do I print to the file?

I am working through an assignment and have run into a few snags.
My program prints output to the screen, (not how I need it yet) but only prints the first entry to the file. Below is a snippet of the code. The file appears to be reading in the data from the input file, but the loop does not output to the file past the first entry.
Scanner in = new Scanner(System.in); //Scanner object to read input from the file
System.out.println("Enter filename to read "); //file name prompt
String inputFileName = in.nextLine(); //line input reads next line
/*
* TODO 2) Use an unbuffered file input stream to open listings.txt file
* and read in property listings.
*/
Scanner reader = null;
try {
reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
return;
}
PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) { //It needs to output to the text file. Currently a file is created, but it is empty?
Scanner s2 = new Scanner(reader.next());
#SuppressWarnings("unused")
boolean b;
while (b = s2.hasNext()) {
String output = s2.next();
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2); //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason?
}
Even if you are using automatic flushing, which you aren't in this case, the PrintWriter object would output anything in its internal buffer unless you do one of two things:
1) Use the println(), printf(), or format() to methods
2) Make a call to the flush() method every time you print, this way all of the data in the internal buffer gets written out.
Note: The print() method does not cause the PrintWriter object to flush() its buffer.
try adding a call to flush() after you call print()
Example of split()
PrintWriter out = new PrintWriter("agentreport.txt");
while (reader.hasNextLine()) {
String words = reader.nextLine().split();
#SuppressWarnings("unused")
boolean b;
for(String word : words) {
String output = word ;
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2);
}
One thing that immediately jumps out is that you aren't handling your resources properly.
Any time you use an IO resource such as a reader/database connection/etc., you should always close it using a finally block, using this sort of pattern:
Reader reader = /* construct it however */
try {
/* do something with the reader */
}
finally {
reader.close();
}
If you don't do this, there's no guarantee that the reader will actually be closed, and your application will leak file descriptors/connection pool connections/etc., until eventually it won't be able to get hold of any more and your app crashes. (This won't always have fatal consequences, but it's such a straightforward pattern you should use it every time until it becomes automatic).
In this case, you aren't closing your writer at all, which means that it's not guaranteed that it ever actually flushes its output to the file. It would be perfectly in accordance with the Writer interface for it to write everything or nothing - without the flush, you have no guarantees. Note that closing the writer will automatically call flush, so that's the best bet once you're done with it.
So the latter part of your code should look like:
PrintWriter out = new PrintWriter("agentreport.txt");
try {
// Existing code here
}
finally {
// This closes the file and frees the descriptor, but also flushes the buffers
out.close();
}
Also, how are you handling the IOExceptions that can be thrown by the reading and writing? Are you catching them and swallowing them somewhere? If so, it's possible that your code is throwing an exception telling you exactly why it can't write, and you're just ignoring it and then looking puzzled.
Not to put too fine a point on it, error handling is probably the most significant part of good software development. It's not too hard to write software that works when everything's fine; the most challenging part is handling things well when you run out of space on the hard drive, or the network is temporarily down, etc.
In this case the most pragmatic approach would be to just let the exception be thrown out of the top of your main method. In this case your application will "crash", and you'll get a stacktrace + error message on the console, which will make it immediately clear that something went wrong, and give you a very good idea of what it was.
try
out.println(output2);
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
also I'd use a var other than "out" as when system.out is imported to use the shortcode 'out.println()', this could cause variable confusion
edit: good point #Hunter McMillen, changed to println as append is for a CharSequence.
try (
Scanner reader = new Scanner(new File(inputFileName));
PrintWriter writer = new PrintWriter(new FileOutputStream("agentreport.txt"), true);
) {
while (reader.hasNextLine()) {
String output = reader.nextLine().toUpperCase();
System.out.println(output);
writer.println(output);
}
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
}

Categories