BufferReader in Java - java

I have a problem with BufferReader and OutputStream in Java. My aim: when you insert something from a keyboard - it goes to the file. How should I correct my code?
import java.io.*;
class IntoFile {
public static void main(String[] args) throws Exception{
try {
BufferedReader sisse = new BufferedReader(new InputStreamReader(System.in));
System.out.print ("Insert something: ");
String s = sisse.readLine();
byte[] buf = new byte[1024];
OutputStream valja = new FileOutputStream(new File(args[0]));
String line = null;
while ((line = br.readLine()) != null) {
}
valja.close();
}
catch (IOException e) {
System.out.println ("I/O: " + e);
}
}
}
Thanks!

I'd use Scanner and PrintWriter
C:\Documents and Settings\glowcoder\My Documents>javac Dmitri.java
C:\Documents and Settings\glowcoder\My Documents>java Dmitri
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>more out.txt
test
woohoo
quit
C:\Documents and Settings\glowcoder\My Documents>
Code:
import java.io.*;
import java.util.*;
class Dmitri {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter("out.txt");
while(in.hasNextLine()) {
String line = in.nextLine();
out.println(line);
out.flush(); // not necessary every time, but simple to do so
if(line.equalsIgnoreCase("QUIT")) break;
}
out.close();
}
}

HI I am providing a sample code through which you can write in the file after user enters characters or line from keyboard.
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
In the our.write pass the line(variable) string argument and the string will be written in that file.

Related

Cannot find symbol when using bufferwriter.readline()

I'm trying to learn java but I don't know why I'm getting there errors.What I basically want is that user will input new characters and will be written to the file as long it is not the word "stop"(program terminates at this point).
Can you guys help me?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
You are trying to read from writer which you can't. You already have scanner and using it, you could read form System input i.e. Keyboard.
Change your line like:
From
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
To
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
You are trying to read from your output, not your input
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}

Trying to Read text line by line and write into output file each line in Java

I am trying to read data from a text file (line by line) and I want to write into output file the lines I read from the flies.
Here is how I programmed my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class read {
public static void main(String args[])
{
String input = null;
input = readFile();
writeFile(input);
}
public static void writeFile(String in)
{
String fileName = "output.txt";
//String payload = null;
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw =new BufferedWriter(fw);
bw.write(in);
System.out.println("Received "+in.length()+" bytes: ");
bw.close();
}
catch(IOException ex) {
System.out.println("Error writing to file '"+ fileName + "'");
}
}
public static String readFile()
{
String fileName = "temp.txt";
String line = null;
String Sentence = null;
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
//Sentence += line+'\n';
Sentence = line +'\n';
}
br.close();
System.out.println("Sending file "+fileName);
return Sentence;
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
return null;
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
return null;
// Or we could just do this:
// ex.printStackTrace();
}
}
}
text file:
I returned##% from the City about three o'clock on that
May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
Output:
The read method reads first line from the text file and writes that line into output file...
I am new in programming and would really appreciate help!
For creating the output file, try this:
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(in);
writer.close();
When you read from the file you should append the lines to your original variables by doing
Sentence += line+'\n';

java serialization and deserializaion

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();
}
}
}
}
}

Read data from a text file using Java

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines.
Snippet used :
while(fis.available() > 0)
{
char c = (char)fis.read();
.....
.....
}
You should not use available(). It gives no guarantees what so ever. From the API docs of available():
Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
You would probably want to use something like
try {
BufferedReader in = new BufferedReader(new FileReader("infilename"));
String str;
while ((str = in.readLine()) != null)
process(str);
in.close();
} catch (IOException e) {
}
(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)
How about using Scanner? I think using Scanner is easier
private static void readFile(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Read more about Java IO here
If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
// Do something with line
}
(Note that this code doesn't handle exceptions or close the stream, etc)
String file = "/path/to/your/file.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
// Uncomment the line below if you want to skip the fist line (e.g if headers)
// line = br.readLine();
while ((line = br.readLine()) != null) {
// do something with line
}
br.close();
} catch (IOException e) {
System.out.println("ERROR: unable to read file " + file);
e.printStackTrace();
}
You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here
and you can use the following method:
FileUtils.readFileToString("yourFileName");
Hope it helps you..
The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0
In Java 8 you could easily turn your text file into a List of Strings with streams by using Files.lines and collect:
private List<String> loadFile() {
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
List<String> list = null;
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
//The way that I read integer numbers from a file is...
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String [] args) throws IOException
{
Scanner input = new Scanner(new File("cards.txt"));
int times = input.nextInt();
for(int i = 0; i < times; i++)
{
int numbersFromFile = input.nextInt();
System.out.println(numbersFromFile);
}
}
}
Try this just a little search in Google
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("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
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());
}
}
}
Try using java.io.BufferedReader like this.
java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
Yes, buffering should be used for better performance.
Use BufferedReader OR byte[] to store your temp data.
thanks.
user scanner it should work
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
public class ReadFileUsingFileInputStream {
/**
* #param args
*/
static int ch;
public static void main(String[] args) {
File file = new File("C://text.txt");
StringBuffer stringBuffer = new StringBuffer("");
try {
FileInputStream fileInputStream = new FileInputStream(file);
try {
while((ch = fileInputStream.read())!= -1){
stringBuffer.append((char)ch);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File contents :");
System.out.println(stringBuffer);
}
}
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
File file = new File("Path");
FileReader reader = new FileReader(file);
while((ch=reader.read())!=-1)
{
System.out.print((char)ch);
}
This worked for me
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}

Continually read the lines being appended to a log file

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();
}
}
}

Categories