Saving input to a file is replaced when re-running - java

I'm trying to create something similar to a mail server.
Now, I'm supposed to have a file called 'Credentials' that saves the email and password entered each time I run the client.
File Credentials = new File("Server\\Credentials.txt");
try{
if(Credentials.createNewFile()){
System.out.println("Credentials created");
}else {System.out.println("Credentials already exists");}
}catch(Exception error){}
try (
PrintWriter out = new PrintWriter(Credentials, "UTF-8")
) {
out.println("Email: " + email);
out.println("Password: " + password);
} catch(IOException e) {
e.printStackTrace();
}
However, each time a client runs, it replaces the old email and password. Any idea how to make it continue to the next line without replacing? Thank you.

As previously mentioned you have to use the correct constructor, which will append your text instead of overriding.
But I would suggest to do it this way:
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
doSomething("test" + i);
}
}
static void doSomething(String text) {
try (PrintWriter test = new PrintWriter(new BufferedWriter(new FileWriter("your path", true)))) {
test.print(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here are some further informations and different approaches for your issue:
How to append text to an existing file in Java?

Related

why I can't add my answer to readwrite.txt.?

I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.
public static void main(String[] args) {
ArrayList<String> category1=new ArrayList<>();
category1.add("die hard");
category1.add("7.5");
category1.add("mission impossible");
category1.add("8");
category1.add("the expendabels");
category1.add("6");
ArrayList<String> category2=new ArrayList<>();
category2.add("the mask");
category2.add("due date");
ArrayList<String>userchoices=new ArrayList<>();
Scanner s= new Scanner(System.in);
System.out.println("select a movie");
String answer=s.nextLine();
String writepath="files/readwrite.txt";
try {
FileWriter writer=new FileWriter(writepath);
writer.write(answer);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (category1.contains(answer)) {
System.out.println(category1.get(category1.indexOf(answer) + 1) +
(" of 10"));
System.out.println("action");
}
if (answer.equals("action"))
System.out.println(category1);
else if (category2.contains(answer))
System.out.println("comedy");
if (answer.equals("comedy"))
System.out.println(category2);
}
}
I try to add my answer to readwrite.txt, but I don't find my answer every time I run the code.
You need to close your FileWriter when you are done with writing to file. When you call close() writer will flush its internal buffer to disk and you will see that text appears in file. Also it is a must to close any resources when you do not need them.

Java capturing telnet output in file

I am trying to telnet to a server, run a command and put the output of that command in a file.
I can get the command in the file but not the result of this command.
I cannot see my output on my console either, so I assumed it run but I am not sure.
Does anybody have any idea?
public final static void main(String[] args) throws IOException, InterruptedException
{
FileOutputStream fout = null;
try
{
fout = new FileOutputStream ("spyfile.log");
}
catch (IOException e)
{
System.err.println(
"Exception while opening the spy file: "
+ e.getMessage());
}
TelnetClient telnet;
telnet = new TelnetClient();
try
{
telnet.connect("myserver", 23);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
telnet.registerSpyStream(fout);
PrintStream out = new PrintStream( telnet.getOutputStream() );
out.println( "mycommand" );
try
{
telnet.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
fout.close();
System.exit(0);
}
I am not sure what is TelneClient, if this is Commons Net class, then you are missing the part that actually reads data exchanged during telnet session. Please run this example and see how it works, once you get it you'll be able to cut it to your needs.

FileOuputStream Write bytes for loop, but no data write?

Listing my program fragment as below
public class InStream {
static FileOutputStream file=null;
static {
try {
file = new FileOutputStream("deo.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
//when i try to replace below infinite loop,
//it is also not able to output my String
//while(ture)
or
//for(;;)
for(int i=0;i<100000;i++){
file.write("AB ".getBytes());
}
//file.flush();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Run this program -> open deo.txt -> there are no data within this file
but when i comment the for loop just only test below fragment code:
try {
file.write("AB ".getBytes());
file.close();
} catch (Exception e) {
e.printStackTrace();
}
Now i can see the "AB " string in the file. so strange....
Can any one do me a favor?
There is no error in your code. File "deo.txt" must be generate which contains AB AB...............
I tested your code. And it works. But for the deo.txt. You can check its size if it is about 293k. It displays nothing if you open it with Eclipse text editor. But you can view it with other system editor, such as notepad++.

Java - passing input into external C/C++ application

I'm trying to enter some value in external application using Java.
Java application looks like this:
Runtime runtime = Runtime.getRuntime();
// ... str build ...
proc = runtime.exec(str);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
bw.write(value);
bw.flush();
bw.close();
if (proc.waitFor() != 0)
// error msg
// the end
Application hangs at waitFor method.
External application looks like this:
welcome banner
please enter 8 character input:
Welcome banner is printed using printf and input is taken with SetConsoleMode/ReadConsoleInput. ReadConsoleInput reads one char and they are masked with * character.
Help
you can use:
proc.getOutputStream().write("some date".getBytes())
keep in mind that you HAVE to read everything the app send to stdout and stderr, else it might get stuck writing there.
I use a generic class to read it in a different thread.
usage is like:
InputStreamSucker inSucker = new InputStreamSucker(proc.getInputStream());
InputStreamSucker errSucker = new InputStreamSucker(proc.getErrorStream());
proc.waitFor();
int exit = process.exitValue();
inSucker.join();
errSucker.join();
InputStreamSucker code is here:
public class InputStreamSucker extends Thread
{
static Logger logger = Logger.getLogger(InputStreamSucker.class);
private final BufferedInputStream m_in;
private final ByteArrayOutputStream m_out;
private final File m_outFile;
public InputStreamSucker(InputStream in) throws FileNotFoundException
{
this(in, null);
}
public InputStreamSucker(InputStream in, File outFile) throws FileNotFoundException
{
m_in = new BufferedInputStream(in, 4096);
m_outFile = outFile;
m_out = new ByteArrayOutputStream();
start();
}
#Override
public void run()
{
try
{
int c;
while ((c = m_in.read()) != -1)
{
m_out.write(c);
}
}
catch (IOException e)
{
logger.error("Error pumping stream", e);
}
finally
{
if (m_in != null)
{
try
{
m_in.close();
}
catch (IOException e)
{
}
}
try
{
m_out.close();
}
catch (IOException e)
{
logger.error("Error closing out stream", e);
}
if (m_outFile != null)
{
byte data[] = m_out.toByteArray();
if (data.length > 0)
{
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(m_outFile);
fo.write(data);
}
catch (IOException e)
{
logger.error("Error writing " + m_outFile);
}
finally
{
try
{
if (fo != null) fo.close();
}
catch (IOException e)
{
logger.error("Error closing " + m_outFile);
}
}
}
}
}
}
public String getOutput()
{
return new String(m_out.toByteArray());
}
}
Got the answer! The trick is to use WriteConsoleInput() API because program expects keyboard event, not text ... That's why the waitFor() waited forever! :)

Java URL Connection blank input stream

The application I am working on has a terribly slow loading web page. If I run the following code it works fine but only because of the call to sleep. If I don't sleep then the InputStream is just a bunch of spaces, probably due to the application it is calling from. Is there any non-hack way around this?
public class PublishTool extends Thread {
private URL publishUrl;
private String filerLocation;
public PublishTool() {
}
public PublishTool(String publishUrl, String filerLocation) throws NibException {
try {
this.publishUrl = new URL(publishUrl);
} catch (MalformedURLException e) {
throw new NibException("Publish Url :" + publishUrl + " is not valid. ");
}
this.filerLocation = filerLocation;
}
public void run() {
File filerFile = new File(filerLocation);
BufferedWriter writer = null;
try {
URLConnection conn = publishUrl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream())));
writer = new BufferedWriter(new FileWriter(filerLocation));
Thread.sleep(1000l);
while (reader.ready()) {
writer.write(reader.readLine() + "\n");
}
} catch (MalformedURLException e) {
throw new IllegalStateException("Malformed URL for : " + publishUrl + " " + filerLocation, e);
} catch (IOException e) {
throw new IllegalStateException("IO Exception for : " + publishUrl + " " + filerLocation, e);
} catch (InterruptedException e) {
throw new IllegalStateException("Thread was interrupted early... publishing might have failed.");
} catch (NibException e) {
throw new IllegalStateException("Publishing File Copy failed : " + filerLocation + ".bak" + " to " + filerLocation);
} finally {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't use reader.ready(). Just call readLine() and let readLine() block until the data's ready. The end of the data will generally be signalled with a null line.
In case its helpful, a couple of code examples on my web site: reading from a URL.
Firstly, it would be helpful if you posted your actual code.
My guess the problem is calling Reader.ready. Similar to InputStream.available, that returns true if there is already buffered input. If it needs to wait for, say, a socket the it will return false. Generally you don't need ready. Use readLine, and break out of the loop if it returns null (for end of stream).

Categories