I have to output the method sayHello() twice.
The output should be written to the console, and once in a file.
I wrote some code but I don't get ahead.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Utility {
public static void main(String[] args){
try(OutputStream src = new FileOutputStream("C:/Users/baum/Documents/TestText.txt");
InputStream dest = new FileInputStream("C:/Users/baum/Documents/TestText.txt")){
sayHello(src, dest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sayHello(OutputStream src, InputStream dest)throws IOException{
String t = "Hello World!!!";
OutputStreamWriter out = new OutputStreamWriter(src);
InputStreamReader in = new InputStreamReader(dest);
out.write(t.toCharArray());
out.flush();
in.close();
}
}
try {
for (String line : Files.readAllLines(Paths.get("C:\\path\\to\\text.txt"))) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
That's maybe a better way
Related
I am new to Java programming and I was reading the a file using the BufferedInputStream(). Can someone tell me why I can't read my file? If I print obj.read(), it returns -1 everytime. Instead it should return the unicode value of every character that the stream is reading.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
while(obj2.read()!=-1)
{
System.out.print((char) obj2.read());
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}
But after introducing a local variable the code works, why???
package com.company;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("riten.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int a;
while((a=obj2.read())!=-1)
{
System.out.print((char)a);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
}
You need to read from your BufferedInputStream and not from the FileInputStream. You are mixing things here.
But in addition to your code you need to properly handle streams, i.e. when you open a file you need to close those afterwards.
A fix of your code. I added a local variable to store the read character and then cast it to a character.
public static void main(String[] args) {
try {
FileInputStream obj = new FileInputStream("myfile.txt");
BufferedInputStream obj2= new BufferedInputStream(obj);
int c;
while((c = obj2.read())!=-1)
{
System.out.print((char) c);
}
}
catch (Exception e)
{
System.out.println(e);
}
System.out.println("program executed");
}
So I have a real strange bug, I get my objects into a arraylist, write them out to see if everything is there, everything checks out, i write them down into a file, eveything is there when I open the file, but when i go on to read them some objects are for unknow reasons not read, like that entry isnt exisitng in the file, but I can see in the file that they are there. Anyone know that I'm missing here?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class ReadWriteTD {
public static void write(ArrayList<Tokendata> list) {
try {
FileOutputStream f = new FileOutputStream(new File("src/resources/TokenProfiles"));
ObjectOutputStream o = new ObjectOutputStream(f);
// Write objects to file
list.forEach(a -> {
try {
o.writeObject(a);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
o.close();
f.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error initializing stream");
}
}
public static ArrayList<Tokendata> read() {
ArrayList<Tokendata> list = new ArrayList<Tokendata>();
try {
FileInputStream fi = new FileInputStream(new File("src/resources/TokenProfiles"));
ObjectInputStream oi = new ObjectInputStream(fi);
Boolean cond = true;
while(cond){
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
else cond=false;
}
oi.close();
fi.close();
}catch(Exception e){
}
//list.forEach(a -> System.out.print(a.toString()));
return list;
}
}
This is the problem:
if(oi.readObject() != null)
list.add((Tokendata) oi.readObject());
That's calling readObject() twice per iteration. The result of the first call is ignored other than to check whether or not it's null. You just want something like:
Object obj;
while ((obj = oi.readObject()) != null) {
list.add((Tokendata) obj);
}
No need for your cond variable, and now you're only calling readObject once per iteration.
for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}
Disk.class implementation
package server;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import services.CustomerData;
public class Disk implements MessageListener{
private int index;
private FileWriter f;
private BufferedWriter b;
public Disk(int i){
this.index=i;
try {
f = new FileWriter("disk"+i+".txt",true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b = new BufferedWriter(f);
}
#Override
public void onMessage(Message m) {
try {
if(m instanceof ObjectMessage){
CustomerData c = (CustomerData) ((ObjectMessage) m).getObject();
b.write(c.getSurname()+" "+c.getName()+" "+c.getAge());
b.newLine();
b.flush();
System.out.println("disk"+index+".txt saved");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So, what happens is that every message received by every message listener is saved in the same file (the last indexed disk.txt file) but I want to save them in every single file, from 0 to N. N txt files are created but they are not modified except the last one.
EDIT: I added the FileWriter and BufferedWriter in the Disk contructor but it will create N files but modify the last one only.
Main class there Disk is created:
package server;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.jms.JMSException;
import javax.jms.Session;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class StorageServer {
public static final int N = 10;
public static void main(String[] args) throws RemoteException {
Hashtable<String,String> prop = new Hashtable<String,String>();
prop.put("java.naming.factory.initial", "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
prop.put("java.naming.provider.url", "tcp://127.0.0.1:61616");
prop.put("topic.req", "requests");
System.setProperty("org.apache.activemq.SERIALIZABLE_PACKAGES","*");
try {
Context jndiCon = new InitialContext(prop);
TopicConnectionFactory tConnFact = (TopicConnectionFactory) jndiCon.lookup("TopicConnectionFactory");
TopicConnection tConn = tConnFact.createTopicConnection();
TopicSession tSess = tConn.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = (Topic) jndiCon.lookup("req");
TopicSubscriber subscriber = tSess.createSubscriber(topic);
tConn.start();
for(int i=0; i<N; i++){
//FileWriter file = new FileWriter("disk"+i+".txt",true);
subscriber.setMessageListener(new Disk(i));
System.out.println("New disk"+i+" started");
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You have a single TopicSubscriber which has a single MessageListener (hence the setMessageListener and not addMessageListener). You need to create a separate TopicSubscriber for each listener with
for(int i=0; i<N; i++){
TopicSubscriber subscriber = tSess.createSubscriber(topic);
subscriber.setMessageListener(new Disk(i));
System.out.println("New disk"+i+" started");
}
I'd also recommend avoiding using the FileWriter (and FileReader) class, because it uses the platform encoding. This can cause surprises when platform (or its encoding) changes. The equivalent, but longer and safer way is:
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("whatever.txt"), "UTF-8"));
With UTF-8 being a safe encoding to use.
Test1_Exec.java
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("java -cp bin Test1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1.java:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args)
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test1_Exec.class and Test1.class are both in the bin folder under JavaTest(project name), and the codes do work. But I want to replace the code "Process p = run.exec("java -cp bin Test1")" with "Process p = run.exec("java Test1")" by adding bin folder( right clikcing JavaTest(project name)->Run As->Run Configuration | Tab Classpath --- User Entries --- Advanced --- Add Folders ), then Test1.txt is not created by new codes. So where is the problem ?
To me program seemed unnecessarily complex. Why not below(if you dont have specific requirement)
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
try {
Test1.createFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void createFile()
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}