I wrote a program to write in a file...
package iofile;
import java.io.*;
public class WriteFile {
public static void main(String[] args) {
String s;
File file=new File("C:\\Users\\Rajesh\\oacert\\Learn\\src\\iofile\\raj.txt");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
try{
PrintWriter pr=new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
System.out.println("enter to write in a file...");
s=br.readLine();
while(s!=null){
pr.println(s);
s=br.readLine();
}
pr.close();
}
catch(Exception e){
}
}
}
But it's unable to write anything in raj.txt. What's causing this? Thanks in Advance
NOTE: raj.txt exists in the mentioned directory...
I don't think s can ever be null in your code. You should better use a terminating string to exit the program. Try replacing this:
while(s!=null){
with
while(!s.equals("exit")){
and enter 'exit' to terminate the loop
Use write method.
Put an end condition, such as s.equalsIgnoreCase("Exit")
Call method flush;
Try the following code.
while(!s.equalsIgnoreCase("Exit")){
pr.write(s);
pr.write("\n");
s=br.readLine();
}
pr.flush();
pr.close();
Related
I have created a text file named 'Month.txt' which contains this String: "January February March".
This is my program below which deletes "February" from the text file:
import java.io.*;
import java.util.*;
class Delete_element_from_txtfile
{
public static void main()throws IOException
{
FileReader fr=new FileReader("Month.txt");
BufferedReader br=new BufferedReader(fr);
FileWriter fw=new FileWriter("Month.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
String str;
String newstr="";
while((str=br.readLine())!=null)
{
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
String month=S.nextToken();
if(month.equals("February"))
{
continue;
}
else
newstr=newstr+(month+" ");
}
}
pw.print(newstr);
pw.close();
bw.close();
fw.close();
br.close();
fr.close();
}
}
However after running the program, when I open the file, it's all empty. I have just started file handling in java, so I have no clue of what's going on. I would like some help on this problem. Thanks!
You are opening Same file for reading and writing is the issue. Because you are opening file for write immediately after reading and hence it is overwriting the current data.
Just move the Writing code after file reader is closed.
Here is updated code:
public static void main(String []ars)throws IOException
{
FileReader fr=new FileReader("Month.txt");
BufferedReader br=new BufferedReader(fr);
String str;
String newstr="";
while((str=br.readLine())!=null)
{
StringTokenizer S=new StringTokenizer(str);
while(S.hasMoreTokens()==true)
{
String month=S.nextToken();
if(month.equals("February"))
{
continue;
}
else
newstr=newstr+(month+" ");
}
}
br.close();
fr.close();
FileWriter fw=new FileWriter("Month.txt");
BufferedWriter bw=new BufferedWriter(fw);
PrintWriter pw=new PrintWriter(bw);
pw.print(newstr);
pw.close();
bw.close();
fw.close();
}
Here is a much more compact and nicer looking solution:
List<String> lines = Files.readAllLines(Paths.get("Month.txt")); //read every line
//filer out lines that contain february
lines = lines.stream().filer(line -> !line.contains("February")).collect(Collectors.toList());
Files.write(Paths.get("Month.txt"), lines, Charset.defaultCharset()); //write it back
No need to close file reading streams manually, no need to use while loops, and classes like StringTokenizer!
So, I'm trying to make a program that can write and then read the exact same text file using only FileWriter and FileReader, but for some reason, when I put both of these classes at the same code, FileWriter works properly, but FileReader does not, and I get an empty output.
import java.io.*;
import java.util.Scanner;
public class ex2 {
public static void main(String[] args) {
File file = new File("C:\\a.txt");
Scanner scanner = new Scanner(System.in);
try {
FileReader reader = new FileReader(file);
FileWriter writer = new FileWriter(file);
writer.write(scanner.nextLine());
int ch;
while ((ch = reader.read()) != -1) {
System.out.println((char)ch);
}
scanner.close();
reader.close();
writer.close();
} catch (Exception e) {
}
}
}
That's the code I'm talking about. I can write anything to a.txt, but reader does not seem to be able to read a thing. The weird part is, if I use the exact same code but without the file writing parts, FileReader works normally as it should. What am I doing wrong? Thanks in advance!
FileWriter objects are buffered. That means they won't write everything you give them as soon as you call write. They'll wait until they have a certain amount to write and then write it all at once. Just add this line:
writer.flush();
between your writing and your reading.
So I'm trying to practice connecting out of one java program to the input of another program and I'm wondering if the way I did it is efficient or if there's a better way. I'm saving a string into a text file in the first program and reading the string then printing it out in the second. Is there a way to just cut out using the text file as a middle man?
Here's my first program:
import java.util.Scanner;
import java.io.*;
public class pip1{
public static void main(String[] args){
String inString = "";
Scanner sc = new Scanner(System.in);
inString = sc.next();
try{
PrintWriter out = new PrintWriter("word.txt");
out.println(inString);
out.close();
} catch(FileNotFoundException ex){ }
}
}
and here is the second:
import java.io.*;
public class pip2{
public static void main(String[] args) {
String fileName = "word.txt";
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String outString = br.readLine();
br.close();
fr.close();
System.out.println(outString);
} catch (FileNotFoundException ex) {}
catch (IOException ex) {}
}
}
Thanks!
I suppose what you want is a pipe, which acts as a "intermediate wire" between two processes without using an "temporary file".
So I recommend you to read doc about Pipes in JAVA.
Here's a link of tutorial.
Also see javadoc about PipedInputStream
javadoc about PipedOutputStream
What's more, if your OS supports IO redirection from terminal, then just do it without using , as Andy says. This would be the easiest.
Just write to System.out in the first one, read from System.in in your second, and use a pipe to connect the output of the first into the second when you run the two commands:
java pip1 | java pip2
I am a beginner Java programmer, and I use this Java Tutorial.
In the I/O from the Command Line page, it uses InputStreamReader cin = new InputStreamReader(System.in); to get user input from the command line. But when I try to use it, nothing happens. I have a very simple program, and it's just to test whether this works, but it doesn't.
import java.io.*;
public class TestInput {
public static void main(String args[]) {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
if(cin.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}
}
It just says, "hello, guest" and exits, without letting me input anything.
I'm assuming this is supposed to work similar to System.console, but if this isn't what it's supposed to be like, please tell me.
What is wrong with my code?
thanks for any answers.
EDIT
From the edits I'm getting, I suppose I have to use cin.readline() to actually read the input.
I got my program to work. thanks!
try{
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
String name= cin.readLine();
if(name!=null && name.equals("jon")) {
System.out.println("hello, jon.");
} else {
System.out.println("hello, guest.");
}
}catch(IOException e){
}
You have to read the input:
if(cin.readLine().equals("jon")) { // or "jon".equals(...) to handle null
(See BufferedReader.readLine())
You will also have to handle the potential IOException with a try-catch.
With cin.equals("jon"), you are testing if the BufferedReader object cin is itself equal to the string "jon", which is clearly false.
You need to use, cin.readLine()
Oracle Docs.
if(cin.readLine().equals("jon"))
Also, you need to handle the IOException
package burak;
import java.io.*;
public class telcon {
public static void main(String[] args) {
try {
String[] command=new String[2];
command[0]="cmd /c start cmd.exe /k \"telnet\"";
command[1]="92.44.0.60";
Process p =Runtime.getRuntime().exec(command);
try {
p.waitFor();
} catch (InterruptedException e) {
System.out.println(e);
}
BufferedReader reader= new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=null;
line=reader.readLine();
File file =new File("rapor.txt");
file.createNewFile();
FileWriter writer=new FileWriter(file);
StringBuilder responseData=new StringBuilder();
while(line!=null) {
System.out.println(line);
responseData.append(line);
writer.write(line);
writer.close();
}
BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream()) );
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while((Error=stdError.readLine())!=null) {
System.out.println(Error);
}
while((Error=stdInput.readLine())!=null) {
System.out.println(Error);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
i want to run telnet execute some commands i have two problem first when i connect to telnet it ask me username and password how ı contineude execute commands by using code after the enter password and my second question inputstream is not working readline is empty all time how can ı fix this problems.thanks for hel
I recommend you the Apache Commons Net Java library (http://commons.apache.org/proper/commons-net/) which contains various clients for many Internet protocols, including Telnet. I don't recommend you to use the embedded telnet client from the OS. Things will be cleaner with a library.
In addtion, in your first while loop, you're closing the writer object every iterations, and you don't read further with your reader.