How do you print out the output in Java Eclipse? - java

I need to physically print out my output box (using a printer) for a class.
Can someone please explain to me how to do this?

Instead of printing the console from eclipse, you can output all your System.out.println() directly to a file. Basically, you are using the file as a debugger instead of the console window. To do this, you can use the code below.
import java.io.*;
PrintWriter writer = new PrintWriter("debuggerOutput.txt", "UTF-8");
//in your class constructor, you will need to add some exception throws
write.println("I used to be in the debugger, but now I go in the file!!")
For each System.out.println(), add an extra write.println() with the same thing in the parenthesis so it outputs to the file what goes in the console.
Then, you will see all your output in a file that you can easily print.
At the end, make sure to write.close()
Full code:
import java.io.*;
public class test {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
PrintWriter writer = new PrintWriter("myFile.txt", "UTF-8");
writer.println("The line");
writer.close();
}
}

Related

I want to chain the"standard" output stream (System.out) to PrintWriter stream. But I can not. Why?

I wanted replaced:
System.out.println("It works properly");
by:
PrintWriter myPrintWriter = new PrintWriter(System.out);
myPrintWriter.print("This text is not displayed on my screen");
Unfortunately this second options does not work and I do not why. I am learning Java from scratch and I am trying to understand some basics problems, concepts so... please, help. And sorry for my English ;)
The stream is not flushed automatically. Use myPrintWriter.flush() to get the result on the console.
Demo:
import java.io.PrintWriter;
class Main {
public static void main(String[] args) {
PrintWriter myPrintWriter = new PrintWriter(System.out);
myPrintWriter.print("This text is not displayed on my screen");
myPrintWriter.flush();
}
}
Output:
This text is not displayed on my screen

FileReader not working in Java

I'm trying to read from a file and it's not working correctly. I've looked at many examples on here and the method I'm using is borrowed from an answer to someone else's question. I'm aware you can use bufferedreader but I'd like to stick with what I know and am learning in my classes right now. When I run this code I just get a blank line, but the file contains 4 lines of information.
import java.io.*;
import java.util.Scanner;
import java.lang.StringBuilder;
import java.io.File;
import java.io.FileInputStream;
public class fileWriting{
public static void main(String[] args) throws IOException{
//Set everything up to read & write files
//Create new file(s)
File accInfo = new File("accountInfo.txt");
//Create FileWriter
Scanner in = new Scanner(new FileReader("accountInfo.txt"));
String fileString = "";
//read from text file to update current information into program
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
fileString = sb.toString();
System.out.println(fileString);
}
}
My file contains the following text:
name: Howard
chequing: 0
savings: 0
credit: 0
One of the advantages of using something like BufferedReader over using Scanner is that you will get an exception if the read fails for any reason. That’s a good thing—you want to know when and why your program failed, rather than having to guess.
Scanner does not throw an exception. Instead, you have to check manually:
if (in.ioException() != null) {
throw in.ioException();
}
Such a check probably belongs near the end of your program, after the while loop. That won’t make your program work, but it should tell you what went wrong, so you can fix the problem.
Of course, you should also verify that accountInfo.txt actually has some text in it.

Java Random Access File strange characters

So I am using the following code to write to a file in Java, the text prints fine, but it has strange characters between the letters.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeChars("#Minecraft server properties");
configFile.close();
}
I was searching for answer and everything pointed to incorrect usage of writeUTF() so I decided to try that instead which semi-fixed the issue, but I still have that character at the beginning of the line.
public static void foo() throws IOException{
static RandomAccessFile configFile;
configFile.writeUTF("#Minecraft server properties");
configFile.close();
}
My questions are: what is that char? Vim shows it as an # and what can I do to remove it?
That char is related with the encoding of the file you are creating.
Try using the following code instead:
public static void createConfigFile() throws IOException {
FileWriter writer = new FileWriter("PATH_TO_YOUR_CONFIG_FILE", false);
writer.append("#Minecraft server properties");
// Append any other content you need here.
writer.flush();
writer.close();
}
Hope that helps!

Java get line total then write to specific line

I'm stuck on writing to a specific line using File, BufferedReader, & BufferedWriter.
What I'm trying to achieve is getting my text files total line count (-3) & writing to that line.
Currently it just erases the whole file & nothing is written.
Image of what I'm doing:
(In Image) line 25 is blank & 26 doesn't contain a doc. it contains "}"
& My code:
package com.tests.writer;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFrame;
public class NewWriter {
static Integer tableCount;
static File file;
static FileWriter fw;
static FileReader fr;
static BufferedWriter bw;
static BufferedReader br;
public static void main(String[] args) {
JFrame frame = new JFrame("Test {New Writer}");
frame.setBounds(500, 500, 500, 500);
frame.setVisible(true);
frame.setResizable(false);
frame.setAutoRequestFocus(true);
try {
startApplication();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void startApplication () throws IOException {
writeToFile ();
}
private static void writeToFile () throws IOException {
Integer lineTCount = 0;
file = new File("Tables.txt");
if (file.exists()) {
fw = new FileWriter(file.getAbsolutePath(), true);
fr = new FileReader(file.getAbsolutePath());
bw = new BufferedWriter(fw);
br = new BufferedReader(fr);
for (String line = br.readLine(); line != null; line = br.readLine()) {
lineTCount++;
System.out.println(lineTCount);
}
System.out.println(lineTCount);
bw.write("Test Text to insert");
System.out.println("done");
System.exit(0);
} else {
file.createNewFile();
System.out.println("New File = " + file.toString());
writeToFile();
}
}
}
If there is an easier way of doing this, I'm open to all idea's as I'm still not familiar with Java.io
& If anyone can tell me this is correct. I may have to add the whole file to a list, add the new text then re-write the file.
There are a few things you did a little bit off.
First and foremost; the reason your file is returning empty is because you aren't calling
bw.close();
After you have finished writing to the file.
I don't know of any way to write to a specific part of a file. I don't think there is one.
What you'll have to do is re-write the file. Basically, make a temporary copy, then write all the lines just as before, except for the third-to-last one.
See this question:
I want to open a text file and edit a specific line in java
(I don't know how to mark questions as duplicate)
BufferedWriter's 'write(String s, int off, int len)' method actually states
Writes a portion of a String.
Note; that is NOT 'writes to a specific location in the file'.
EDIT
I wouldn't use System.exit(0);. That tells your OS 'This execution failed'. You should just let your program close itself normally by excluding this line.
See: When to use system.exit(0)?
The bw pointer does not move when you loop through your file. Use this to write to a specific location in your file. Also why are there two variables lineCount & lineTCount
public void write(String s,
int off,
int len)
throws IOException
Ref: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#write(java.lang.String,%20int,%20int)
EDIT: you are right, my bad. You will have to read the previous contents -> make the changes that you want and rewrite the whole file again.

Why does my program only gets part of web page source?

I have a program to pull the source code of a webpage and save it to a .txt file. It works if done with just one at a time, but when I go through a loop of say 100 pages all of a sudden each page source starts to get cut off between 1/4 and 3/4 of the way through (seems to be arbitrary). Any ideas on why or how I would go about solving this?
Initial thoughts where that the loop is going too fast for the java (I am running this java from a php script) but then thought that it technically shouldn't be going to the next item until the current condition was finished anyway.
Here is the code I'm using:
import java.io.*;
import java.net.URL;
public class selectout {
public static BufferedReader read(String url) throws Exception{
return new BufferedReader(
new InputStreamReader(
new URL(url).openStream()));}
public static void main (String[] args) throws Exception{
BufferedReader reader = read(args[0]);
String line = reader.readLine();
String thenum = args[1];
FileWriter fstream = new FileWriter(thenum+".txt");
BufferedWriter out = new BufferedWriter(fstream);
while (line != null) {
out.write(line);
out.newLine();
//System.out.println(line);
line = reader.readLine(); }}
}
The PHP is a basic mysql_query while(fetch_assoc) grab the url from the database, then run system("java -jar crawl.jar $url $filename");
Then, it fopen and fread the new file, and finally saves the source to database (after escaping_strings and such).
You need to close your output streams after you finish writing each file. After your while loop, call out.close(); and fstream.close();
You must flush the stream and close it.
finally{ //Error handling ignored in my example
fstream.flush();
fstream.close();
}

Categories

Resources