I'm trying to capture the output of a console program and write overwriting lines of the output to a file which another program will read, line by line I write into this file (the file should only contain one line at a time) but when I made this code and tried running it, it didn't work. The process started perfectly, but the file is not being created, written to, and I am not getting any System.out.println's of "Streaming : blah blah blah"
You can read the code below or use this pastebin : http://pastebin.com/raw.php?i=Yahsqxma
import java.io.*;
import java.util.Scanner;
public class OpenRC {
static BufferedReader consoleInput = null;
static String os = System.getProperty("os.name").toLowerCase();
static Process server;
public static void main(String[] args) throws IOException {
// OpenRC by Pacnet2013
System.out.println(System.getProperty("user.dir"));
if(os.indexOf("win") >= 0) {
os = "Windows";
}
else if(os.indexOf("mac") >= 0) {
os = "Mac";
}
else if(os.indexOf("nux") >= 0) {
os = "Linux";
}
switch(os){
case "Linux" : //cause I need WINE
File file = new File(System.getProperty("user.dir") + "/OpenRC.txt");
try {
Scanner scanner = new Scanner(file);
String path = scanner.nextLine();
System.out.println("Got BlocklandEXE - " + path);
String port = scanner.nextLine();
System.out.println("Got port - " + port);
scanner.close();
server = new ProcessBuilder("wine", path + "Blockland.exe", "ptlaaxobimwroe", "-dedicated", "-port" + port).start();
if(consoleInput != null)
consoleInput.close();
consoleInput = new BufferedReader(new InputStreamReader(server.getInputStream()));
streamLoop();
} catch (FileNotFoundException e) {
System.out.println("You don't have an OpenRC Config file OpenRC.txt in the directory of this program");
}
}
}
public static void streamConsole()
{
String line = "";
int numLines = 0;
try
{
if (consoleInput != null)
{
while((line = consoleInput.readLine()) != null && consoleInput.ready())
{
numLines++;
}
}
}
catch (IOException e)
{
System.out.println("There may be a problem - An IOException (java.io.IOException) was caught so some lines may not display / display correctly");
}
if(!line.equals("") && !(line == null))
{
System.out.println("Streaming" + numLines + line);
writeToFile(System.getProperty("user.dir"), line);
}
}
public static void streamLoop()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("A slight problem may have happened while trying to read a command");
}
streamConsole();
streamLoop(); //it'll go on until you close this program
}
public static void writeToFile(String filePath, String content)
{
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
System.out.println("Creating new stream text file");
}
FileWriter writer = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(writer);
bw.write(content);
bw.close();
System.out.println("Wrote stream text file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are running a DOS console application, which does not necessarily write to stdout or stderr, but it writes to the "console". It's nearly impossible to capture the "console" output reliably. The only tool that I have ever seen that is able to capture console output is expect by Don Libes, and that does all sorts of hacks.
Related
I need my program to print this file line by line, waiting for the user to press enter between each one. My code keeps printing the whole excerpt. What do I need to change?
import java.io.*;
import java.util.*;
public class NoteCopier {
public static void main(String[] args) throws IOException {
System.out.println("Hello! I copy an excerpt to the screen line for line"
+ " just press enter when you want a new line!");
try {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String line = reader.readLine();
Scanner scan = new Scanner(System.in);
while(true) {
String scanString = scan.nextLine();
if(line != null) {
if(scanString.isEmpty()){
System.out.println(line);
line = reader.readLine();
}
else {
scanString = null;
break;
}
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
If line is null you'll loop forever; the nested if statements.
I did it in the new Stream style, without the ubiquitous but needless Scanner on System.in.
private void dump(String file) {
Path path = Paths.get(file);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
System.out.println(line);
if (lineCounter.get() == 0) {
String input = null;
try {
input = con.readLine();
} catch (IOException e) {
}
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
With CtrlD you can exit on Windows I believe.
I have added that a line with a Space will dump the next 10 lines.
The ugly thing are the user input lines.
With java.io.Console one can ask input with a String prompt, which then can be used to print the file's line as prompt.
private void dump(String file) {
Path path = Paths.get(file);
Console con = System.console();
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
if (lineCounter.get() == 0) {
//String input = con.readLine("%s |", line);
String input = new String(con.readPassword("%s", line));
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
System.out.println(line);
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
Using a prompt with the file's line, and asking a non-echoed "password" will be sufficient okay. You still need the Enter.
There is one problem: you must run this as real command line. The "console" in the IDE uses System.setIn which will cause a null Console. I simply create a .bat/.sh file. Otherwise System.out.print(line); System.out.flush(); might work on some operating system.
I have one input.txt file which consist on let suppose 520 lines.
I have to make a code in java which will act like this.
Create first file named file-001.txt from first 200 lines. then create another file-002 from 201-400 lines. then file-003.txt from remaining lines.
I have coded this, it just write first 200 lines. What changes I need to make in order to update its working to above scenario.
public class DataMaker {
public static void main(String args[]) throws IOException{
DataMaker dm=new DataMaker();
String file= "D:\\input.txt";
int roll=1;
String rollnum ="file-00"+roll;
String outputfilename="D:\\output\\"+rollnum+".txt";
String urduwords;
String path;
ArrayList<String> where = new ArrayList<String>();
int temp=0;
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
++temp;
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void filewriter(String linetoline,String filename) throws IOException{
BufferedWriter fbw =null;
try{
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(filename, true), "UTF-8");
fbw = new BufferedWriter(writer);
fbw.write(linetoline);
fbw.newLine();
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
fbw.close();
}
}
}
One way can be use of if else but I cant just use it because my actual file is 6000+ lines.
I want this code to work like I run the code and give me 30+ output files.
You can change the following bit:
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
to this:
dm.filewriter(line, "D:\\output\\file-00" + ((temp/200)+1) + ".txt");
This will make sure first 200 lines go to first file, next 200 lines go to next file and so on.
Also, you might want to batch 200 lines together and write them in one go rather than creating a writer everytime and write to file.
You may have a method that creates the Writer to the current File, reads up to limit number of lines, closes the Writer to the current File, then returns true if it had enough to read , false if it couldn't read the limit number of lines (i.e, abort next call, don't attempt to read more lines or write next file).
Then you would call this in a loop , passing the Reader, the new file name, and the limit number.
Here is an example :
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class DataMaker {
public static void main(final String args[]) throws IOException {
DataMaker dm = new DataMaker();
String file = "D:\\input.txt";
int roll = 1;
String rollnum = null;
String outputfilename = null;
boolean shouldContinue = false;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
do {
rollnum = "file-00" + roll;
outputfilename = "D:\\output\\" + rollnum + ".txt";
shouldContinue = dm.fillFile(outputfilename, br, 200);
roll++;
} while (shouldContinue);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean fillFile(final String outputfilename, final BufferedReader reader, final int limit)
throws IOException {
boolean result = false;
String line = null;
BufferedWriter fbw = null;
int temp = 0;
try {
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(outputfilename, true), "UTF-8");
fbw = new BufferedWriter(writer);
while (temp < limit && ((line = reader.readLine()) != null)) {
temp++;
fbw.write(line);
fbw.newLine();
}
// abort if we didn't manage to read the "limit" number of lines
result = (temp == limit);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
fbw.close();
}
return result;
}
}
I am trying to design two different methods for a Java application. The first method will pass in a string of the name of a file, and return the text of a text file as a string. The second method will pass in the name of a file and the text, and create a new text file and output the string into the file.
Currently my code works without the methods, but I am trying to design it with a separation of concerns and low coupling. I am trying to modify it so I can just call a method to output any sort of data I have in a string to a text file.
Here is my code without the methods:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
//What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
//What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
//Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: " + outputFile);
// Variables to read and write the files
//Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
}
When creating a method for each of the "read" and "write" portions of my code, I constantly get errors that I assume are from the exception handling. Any thoughts on how to separate code that has exceptions involved?
Think in terms of single responsibility. You have two distinct operations that need to happen: reading and writing.
Let's start with reading. What you're doing right now to read the file surmises these lines:
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
Move that to a method.
private static String readFile(String inputFile) throws IOException {
BufferedReader input;
String total;
String line;// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(inputFile);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
input.close();
return total;
}
Here's what we did:
We have a variable total which is used elsewhere in the program, so that usage has to be preserved. We're returning String and will declare total = readFile(inputFile); on the outside.
We've changed nothing. This code will run the same way as it did without the method.
Now, if we want to move the writing functionality, which is:
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
...we just do.
private static void writeFile(String outputFile, String info) throws IOException {
File file = new File(outputFile);
BufferedWriter output = null;
output = new BufferedWriter(new FileWriter(file));
output.write(info);
System.out.println("The output file: " + outputFile + " has been written.");
output.close();
}
Again, nothing's changed on this method. We don't have any other usages of any of the variables in here to worry about, so we can directly bring it across.
All said, that try block looks a bit anemic:
try {
total = readFile(inputFile);
//Check to make sure we got the text files data
System.out.println("The total string says: \n" + total);
//Call the reverseWords method to switch 'Hello' with 'World'
String info = reverseWords(total);
//Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + info);
writeFile(outputFile, info);
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" +
inputFile + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
...which is a good thing.
I am not sure what are you asking about but try to create your own Exceptions and make your methods throw them like this
package com.qmic.test;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class FileCopier {
public static void main(String[] args) {
// What file should be input for reading?
String inputFile = askForInput("Please enter the name of the file to be read in: ");
// What file should be created to display output ?
String outputFile = askForInput("Please come up with a name of the file to be written backwards: ");
// Check to make sure we got the names
System.out.println("inputFile: " + inputFile + " outputFile: "
+ outputFile);
// Variables to read and write the files
// Call the readTextFile method to read text file into string data
String line = null;
String total = null;
BufferedReader input = null;
try {
String readData = readFileContents(inputFile);
// Check to make sure we got the text files data
System.out.println("The total string says: \n" + readData);
// Call the reverseWords method to switch 'Hello' with 'World'
String reversedContents = reverseWords(readData);
writeToFile(outputFile, reversedContents);
} catch (ReadException ex) {
System.out.println("Error reading file '" + inputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (WriteException ex) {
System.out.println("Error Writing file '" + outputFile + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
public static String reverseWords(String sentence) {
String[] parts = sentence.trim().split("\\s+");
StringBuilder builder = new StringBuilder();
builder.append(parts[parts.length - 1]);
for (int i = parts.length - 2; i >= 0; --i) {
builder.append(" ").append(parts[i]);
}
return builder.toString();
}
public static String askForInput(String question) {
System.out.println(question);
Scanner in = new Scanner(System.in);
String inputFile = in.nextLine();
return inputFile;
}
public static void writeToFile(String fileName, String data)
throws WriteException {
BufferedWriter output = null;
try {
// Check to make sure the string was reversed
System.out.println("The reversed string says: \n" + data);
File file = new File(fileName);
output = new BufferedWriter(new FileWriter(file));
output.write(data);
System.out.println("The output file: " + fileName
+ " has been written.");
}catch(IOException e){
throw new WriteException();
}finally{
try {
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String readFileContents(String fileName) throws ReadException {
// FileReader reads text files in the default encoding.
BufferedReader input = null;
String line = null;
String total = null;
try {
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
input = new BufferedReader(fileReader);
total = input.readLine() + "\n";
while ((line = input.readLine()) != null && total != null) {
total += line + "\n";
System.out.println("Proof that the file says: " + line);
}
} catch (IOException e) {
throw new ReadException();
}finally{
//This is ugly code, if you are using java 7 you have extra option to better this
try {
input.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return total;
}
}
//make me public and move me to a separate file
class WriteException extends IOException {
}
//make me public and move me to a separate file
class ReadException extends IOException {
}
I have created a simple program that serializes String input from cmd to a .ser file.. Part of the requirement is that the program must be able to append new input and be able to read the new input plus the old input.. But i get StreamCorruptedException if i read after the 2nd input..
here is my run on the CMD.. how do I solve this StreamCorruptedException and Why does it happen??. codes are given below.
C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser
Enter text and press ^Z or ^D to end.
hah
haha
hahaha
try
^Z
C:\Users\MSI\Desktop\Codes For Java>java WriteFile cc.ser
Enter text and press ^Z or ^D to end.
asd
asd
asd
asd
asd
^Z
C:\Users\MSI\Desktop\Codes For Java>java ReadFile cc.ser
1: haha
2: haha
3: hahaha
4: hahaha
The Error is :
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1375)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at ReadFile.main(ReadFile.java:23)
WriteFile.java:
import java.io.*;
public class WriteFile implements java.io.Serializable
{
public static void main(String args[])
{
try
{
File myFile = new File(args[0]);
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
ObjectOutputStream oos = new ObjectOutputStream
(new FileOutputStream(myFile,true));
System.out.println("Enter text and press ^Z or ^D to end.");
String str;
while ((str = br.readLine()) != null)
{
oos.writeObject(str);
}
br.close();
oos.close();
}
catch (IOException i)
{
i.printStackTrace();
}
}}
ReadFile.java:
import java.io.*;
public class ReadFile
{
public static void main(String args[])
{
try
{
int ctr = 0;
File myFile = new File(args[0]);
ObjectInputStream OIS = new ObjectInputStream
(new FileInputStream( myFile ));
String str;
while ((str = (String)OIS.readObject()) != null)
{
System.out.println(++ctr + ": " + str);
}
OIS.close();
}
catch (EOFException ex)
{
System.out.println("\nEnd of File Reached ");
}
catch (ClassNotFoundException c)
{
System.out.println("The Error is : ");
c.printStackTrace();
}catch (IOException i)
{
System.out.println("The Error is : ");
i.printStackTrace();
}
}}
This exception occurs whenever u are trying to create a new OutputStream Object for an existing input stream/trying to read even before something is written in which case ,the control information that was read from an object stream violates internal consistency checks.
Use a single OOS and OIS for the life of the socket, and don't use any other streams on the socket.
Also u might want to implement the same using threads in the same program.
If you want to forget what you've written, use ObjectOutputStream.reset().
I think this problem occurs because u are trying to read even before it is written .
i edited my code after reading some answer to this question Appending to an ObjectOutputStream
import java.io.*;
public class WriteFile
implements java.io.Serializable
{
public static void main(String args[])
{
try
{
File myFile = new File(args[0]);
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
if (myFile.exists())
{
AppendingObjectOutputStream AOOS = new AppendingObjectOutputStream(new FileOutputStream(myFile,true));
System.out.println("Enter text and press ^Z or ^D to end.");
String str;
while ((str = br.readLine()) != null)
{
AOOS.writeObject(str);
}
br.close();
AOOS.flush();
}
else
{
ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(myFile,true));
System.out.println("Enter text and press ^Z or ^D to end.");
String str;
while ((str = br.readLine()) != null)
{
OOS.writeObject(str);
}
br.close();
OOS.flush();
}
}
catch (IOException i)
{
i.printStackTrace();
}
}}
and adding a new class from the question mentioned above
public class AppendingObjectOutputStream extends ObjectOutputStream {
public AppendingObjectOutputStream(OutputStream out) {
super(out);
}
#Override
protected void writeStreamHeader() throws IOException {
// do not write a header, but reset:
// this line added after another question
// showed a problem with the original
reset();
}}
any suggestion to better improve this code? sorry just a newbie to java programming
here was my new run on the CMD
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\MSI>cmd
'cmd' is not recognized as an internal or external command,
operable program or batch file.
C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser
Enter text and press ^Z or ^D to end.
a
b
c
d
^Z
C:\Users\MSI\Desktop\Codes For Java>java WriteFile haha.ser
Enter text and press ^Z or ^D to end.
e
f
g
^Z
C:\Users\MSI\Desktop\Codes For Java>java ReadFile haha.ser
1: a
2: b
3: c
4: d
5: e
6: f
7: g
End of File Reached
i did'nt change my readfile.java file... thanks for the answers =D
A couple of questions you need to be clear before heading into your code and fix your coding issue.
1) Why do you need to use ObjectInputStream and ObjectOutputStream? If you are just read and write string, better to use BufferedWriter and BufferedReader. We only use OIS and OOS to read and write object.
2) Your question is nothing related to the Serialization and De-serialization . Please do a google search to see how to do the proper serialize and de-serialize. In your code snippet:
public class WriteFile implements java.io.Serializable // there is no meaning to implement the mark up interface here.
In short, only mark java.io.Serializable on a POJO or data object.
3) When you type ctrl-c or ctrl-z, there is a system interrupt signal triggered, the whole system will stop abruptly, that will cause the corruption of the data writing.
I spent a bit of time to write a complete working sample for you. Hopefully you can get sth from my sample.
ConsoleWriter
/**
* Write Console String to a file
* When you type quit or save it will write to the file in one go.
*
* #author Seabook Chen
*
*/
public class SimpleConsoleWriter {
private static final String NEW_LINE = System.getProperty("line.separator");
public static void main(String[] args) {
if (args == null || args.length == 0) {
throw new RuntimeException("Please specify the file name!!!");
}
String filepath = args[0];
Scanner in = new Scanner(System.in);
System.out.println("Please input your comments ....");
System.out.println("Type quit to finish the input! Please type exact quit to quit!!!");
System.out.println("Type save to write to the file you specified. ");
StringBuilder sb = new StringBuilder();
while(true) {
String input = in.nextLine();
if ("quit".equalsIgnoreCase(input) || "save".equalsIgnoreCase(input)) {
System.out.println("Thanks for using the program!!!");
System.out.println("Your input is stored in " + filepath);
break;
}
sb.append(input);
sb.append(NEW_LINE);
}
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(filepath, true);
bw = new BufferedWriter(fw);
bw.write(sb.toString(), 0, sb.toString().length());
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
SimpleConsoleReader
/**
* Read a file and output in the console
*
* #author Seabook Chen
*
*/
public class SimpleConsoleReader {
public static void main(String[] args) {
if (args == null || args.length == 0) {
throw new RuntimeException("Please specify the file name!!!");
}
File file = new File(args[0]);
FileReader fr = null;
BufferedReader br = null;
String nextLine = null;
try {
fr = new FileReader(file);
br = new BufferedReader(fr);
while((nextLine = br.readLine()) != null ) {
System.out.println(nextLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Concerning my previous question , I found out that maven can't really output jboss console. So I thought I'd like to make workaround it. Here is the deal:
While jboss is running, it writes console logs into server.log file, so I'm trying to retrieve the data as it comes in, because every few seconds the file is changes/updated by jboss I've encountered some difficulties so I need help.
What I actually need is:
read file server.log
when server.log is changed with adding few more lines output the change
Here is the code so far I got, there is a problem with it, it runs indefinitely and it starts every time from the beginning of the file, I'd like it to continue printing just the new lines from server.log. Hope it makes some sense here is the code:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
for(;;){ //run indefinitely
// Open the file
FileInputStream fstream = new FileInputStream("C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
According to the Montecristo suggestion I did this :
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
// Read File Line By Line
while ((line = br.readLine()) != null) {
// Print the content on the console
line = br.readLine();
if (line == null) {
Thread.sleep(1000);
} else {
System.out.println(line);
}
}
// Close the input stream
in.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
And it still not working, it just printed the original file.. although the file changes constantly nothing happens.. nothing gets printed out except the original log file.
HERE IS THE SOLUTION: tnx Montecristo
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
FileInputStream fstream = new FileInputStream(
"C:\\jboss-5.1.0.GA\\server\\default\\log\\server.log");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while (true) {
line = br.readLine();
if (line == null) {
Thread.sleep(500);
} else {
System.out.println(line);
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Also see :
http://vanillajava.blogspot.co.uk/2012/08/java-memes-which-refuse-to-die.html
I don't know if you're going in the right direction but if I've understood correctly you'll find this useful: java-io-implementation-of-unix-linux-tail-f
You can use RandomAccessFile.
import java.io.IOException;
import java.io.RandomAccessFile;
public class LogFileReader {
public static void main( String[] args ) {
String fileName = "abc.txt";
try {
RandomAccessFile bufferedReader = new RandomAccessFile( fileName, "r"
);
long filePointer;
while ( true ) {
final String string = bufferedReader.readLine();
if ( string != null )
System.out.println( string );
else {
filePointer = bufferedReader.getFilePointer();
bufferedReader.close();
Thread.sleep( 2500 );
bufferedReader = new RandomAccessFile( fileName, "r" );
bufferedReader.seek( filePointer );
}
}
} catch ( IOException | InterruptedException e ) {
e.printStackTrace();
}
}
}