How to read objects of arrays from a .txt file? - arrays

First what i have done is write an ArrayList as ann object to a .txt file, what I am trying to do is read back those objects into an array and display the array(reverse of first step). The arraylist i'm passing to the funnctions are salesman and technicians that extend employees with parameters name,number,target,terriorty etc. I get this error when i try to compile it.
Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to Employee
at FileIO.readObject(FileIO.java:165)
at UseCompany.main(UseCompany.java:61)
Trying to read back objects from text file
ArrayList<Employee> use_company_arraylist2 = FileIO.("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt"");
use_company_arraylist2 = FileIO.readObject("C:\\Users\\Saad\\Documents\\writeObjectMethod.txt");
The writing object to text file code:
public static void writeObject(ArrayList<Employee> array_of_employee, String filename)
{
try{
//create file stream and write array to file using stream using objectoutput stream
FileOutputStream fle = new FileOutputStream("c:\\Users\\Saad\\Documents\\writeObjectMethod.txt");
ObjectOutputStream oos = new ObjectOutputStream(fle);
oos.writeObject(array_of_employee);
oos.close();
fle.close();
}
catch(FileNotFoundException filenotfound)
{
System.out.println("FILE NOTE FOUND");
}
catch(IOException ioerror)
{
System.out.println("input or output error");
}
}//end writeObject
The reading object from text file code:
public static ArrayList<Employee> readObject (String filename)
{
ArrayList<Employee> newArrayList = new ArrayList<Employee>();
try
{
FileInputStream readfle = new FileInputStream(filename);
ObjectInputStream readobjectfile = new ObjectInputStream(new BufferedInputStream(readfle));
newArrayList.add((Employee)readobjectfile.readObject());
}
catch(ClassNotFoundException clasnfd)
{
System.out.println("class error?");
}
catch(IOException ioerror)
{
System.out.println("input or output error");
}
return newArrayList;
}//end readObject

An object of type Arraylist can't be casted to an object of Employee class.
This will work
ArrayList list = new ArrayList();
list.add(new Employee());
// for writing arraylist object to file
new ObjectOutputStream(new FileOutputStream(new File("a.txt"))).writeObject(list);
// for reading array list from file
ArrayList<Employee> anotherList = (ArrayList<Employee>) new ObjectInputStream(new FileInputStream(new File("a.txt"))).readObject();
System.out.println(anotherList.size());

Related

Java - Load file as Template + append content in memory and manage byte[]

Im trying load a file in memory with a base information, append lines and include the result into a Zip file. In C# existes MemoryStream but, in java not.
the context of my application is load a stylesheet.css files with a pre-defined styles for add other styles that i get dinamically. Later i want add this content to a zip entry, and i need a byte[] that represent this content.
For the moment, i have the next lines, but i dont know as convert this to byte[]:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
File file = new File(classLoader.getResource("style.css").getFile());
OutputStreamWriter osw = new OutputStreamWriter( new FileOutputStream( file ) );
BufferedWriter writer = new BufferedWriter(osw);
I tried, with ByteArrayOutputStream but i can't completed all my requirements.
Any idea? im opne to other ideas for get my goal. I looking for CSSParser too, but i didn't see as I can append content and get a File document (byte[]) for to add to my zip file.
Finnaly, i didn't find other solution for my problem that convert the InputStream to ByteArrayOutputStream byte to byte.
I created the following methods:
Load template file into Input Stream and convert.
private ByteArrayOutputStream getByteArrayOutputStreamFor(String templateName) {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inStream = classLoader.getResourceAsStream( templateName ); //file into resources directory
ByteArrayOutputStream baos = Utils.toOutputStream(inStream);
return baos;
} catch (Exception e) {
String msg = String.format("erro to loaf filetemplate {%s}: %s", templateName, e.getMessage());
throw new RuntimeException( msg, e.getCause() );
}
}
Copy the inputStream into a ByteArrayOutputStream byte to byte
public static final ByteArrayOutputStream toOutputStream(InputStream inStream) {
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
int byteReads;
while ((byteReads = inStream.read()) != -1) {
outStream.write(byteReads);
}
outStream.flush();
inStream.close();
return outStream;
} catch (Exception e) {
throw new RuntimeException("error message");
}
}
Finally, I append text to ByteArrayOutputStream
ByteArrayOutputStream baosCSS = getByteArrayOutputStreamFor( "templateName.css" );
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( baosCSS ) );
writer.append( "any text" );
writer.flush();
writer.close();
byte[] bytes = baosCSS.toByteArray()

Hadoop Map Reduce - Read HDFS File - FileAlreadyExists error

I am new to Hadoop. I am trying to read an existing file on HDFS using the below code. The configuration seem file and the file path is correct as well. -
public static class Map extends Mapper<LongWritable, Text, Text, Text> {
private static Text f1, f2, hdfsfilepath;
private static HashMap<String, ArrayList<String>> friendsData = new HashMap<>();
public void setup(Context context) throws IOException {
Configuration conf = context.getConfiguration();
Path path = new Path("hdfs://cshadoop1" + conf.get("hdfsfilepath"));
FileSystem fs = FileSystem.get(path.toUri(), conf);
if (fs.exists(path)) {
BufferedReader br = new BufferedReader(
new InputStreamReader(fs.open(path)));
String line;
line = br.readLine();
while (line != null) {
StringTokenizer str = new StringTokenizer(line, ",");
String friend = str.nextToken();
ArrayList<String> friendDetails = new ArrayList<>();
while (str.hasMoreTokens()) {
friendDetails.add(str.nextToken());
}
friendsData.put(friend, friendDetails);
}
}
}
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
for (String k : friendsData.keySet()) {
context.write(new Text(k), new Text(friendsData.get(k).toString()));
}
}
}
I am getting the below exception when I run the code -
Exception in thread "main" org.apache.hadoop.mapred.FileAlreadyExistsException: Output directory hdfs://cshadoop1/socNetData/userdata/userdata.txt already exists
at org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:146)
at org.apache.hadoop.mapreduce.JobSubmitter.checkSpecs(JobSubmitter.java:458)
at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:343)
I am just trying to read an existing file. Any ideas what I am missing here? Appreciate any help.
Exception tells you that your output directory already exists but it should not. Delete it or change its name.
Moreover the name of your output directory 'userdata.txt' looks like the name of a file. So check you are not mistaken in your input/output directories.

JavaMail MimeBodyPart.SaveFile provide corrupted files

I'm using JavaMail Library to parser email mime message.
I'm trying to extract the attached files and save them to the local disk but the saved files are not valid and their size is different from the original. only *.txt file are saved ok but *.PDF or *.xlsx are not.
Can you please help me to fix the code?
My code is:
private static void Test3() {
String email_string = File_Reader.Read_File_To_String("D:\\8.txt");
MimeMessage mm = Email_Parser.Get_MIME_Message_From_Email_String(email_string);
Email_Parser.Save_Email_Attachments_To_Folder(mm,"D:\\TEST");
}
public static String Read_File_To_String(String file_path) {
byte[] encoded = new byte[0];
try {
encoded = Files.readAllBytes(Paths.get(file_path));
} catch (IOException exception) {
Print_To_Console(exception.getMessage(), true,false);
}
return new String(encoded, m_encoding);
}
public static MimeMessage Get_MIME_Message_From_Email_String(String email_string) {
MimeMessage mm = null;
try {
Session s = Session.getDefaultInstance(new Properties());
InputStream is = new ByteArrayInputStream(email_string.getBytes());
mm = new MimeMessage(s, is);
} catch (MessagingException exception) {
Print_To_Console(exception.getMessage(), true, false);
}
return mm;
}
public static void Save_Email_Attachments_To_Folder(MimeMessage mm, String output_folder_path) {
ArrayList<Pair<String, InputStream>> attachments_InputStreams = Get_Attachments_InputStream_From_MimeMessage(mm);
String attachment_filename;
String attachment_filename_save_path;
InputStream attachment_InputStream;
MimeBodyPart mbp;
for (Pair<String, InputStream> attachments_InputStream : attachments_InputStreams) {
attachment_filename = attachments_InputStream.getKey();
attachment_filename = Get_Encoded_String(attachment_filename);
attachment_filename_save_path = String.format("%s\\%s", output_folder_path, attachment_filename);
attachment_InputStream = attachments_InputStream.getValue();
try {
mbp = new MimeBodyPart(attachment_InputStream);
mbp.saveFile(attachment_filename_save_path);
} catch (MessagingException | IOException exception) {
Print_To_Console(exception.getMessage(), true, false);
}
}
}
You're doing something very strange in Save_Email_Attachments_To_Folder. (Not to mention the strange naming convention using both camel case and underscores. :-)) I don't know what the InputStreams are you're collecting, but constructing new MimeBodyParts based on them and then using the new MimeBodyPart to save the attachment to the file is almost certainly not what you want to do.
What exactly is Get_Attachments_InputStream_From_MimeMessage doing? Why iterate over the message to collect a bunch of InputStreams, then iterate over the InputStreams to save them? Why not iterate over the message to find the attachments and save them as you find them using the MimeBodyPart.saveFile method? Have you seen the msgshow.java sample program?

save UDP socket data into file

I have a code to send and receive UDP socket
Send UDP code:
public static void main(String args[]) throws Exception
{
try
{
FileOutputStream fo = new FileOutputStream("OUTFILE.txt");
PrintStream ps = new PrintStream(fo);
DatagramSocket Socket = new DatagramSocket(4555);
byte[] receiveData = new byte[1000000];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while(true)
{
receivePacket.setLength(receiveData.length);
Socket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.printf("RECEIVED: %s " , new String(receivePacket.getData()));
ps.println(sentence);
ps.println();
ps.close();
fo.close();
}
File file = new File("OUTFILE.txt");
FileInputStream fis = new FileInputStream(file);
byte[] fsize = new byte[(int) file.length()];
int size = fis.read(fsize);
System.out.println("Received Size = " + size);
}
catch (Exception e) {
System.err.println(e);
}
}
}
I want to write the value of each received data packet into file then get the size of the whole file.
In my code I just got the first received value written in the file.
Could you please tell me how can I write the whole received value in the file.
At the end of the first loop, you're closing the streams so additional lines can not be written. You need to move the ps.close(); and fs.close() calls to be outside of the loop. In addition, you have an indefinite loop which guarantees that the code reading from the file can not be called--you need to have some mechanism to determine when to stop looping.

Silverlight 5 operation is not allowed on isolated storage

I create a file in isolated storage and then the same file is accessed and be edited on the click of button. But sometime an Exception occured with detail that operation is not allowed on isolated storage. This exception has no fixed time sometimes occured on first click of button some times it occuered after 5th or 6th click etc. ISOFileProcess(String module, String operation, String xmlObj) function in the below code is called on click of button.
public static void ISOFileProcess(String module, String operation, String xmlObj)
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(IsolatedMemFileHandlingCon.fileName) == false)
{
StreamWriter sw = new StreamWriter(store.OpenFile(IsolatedMemFileHandlingCon.fileName, FileMode.OpenOrCreate));
CreateXML(sw,module,operation,xmlObj);
sw.Close();
MessageBox.Show("File Created.");
}
else
{
//store.OpenFile(IsolatedMemFileHandlingCon.fileName, FileMode.Append);
IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(IsolatedMemFileHandlingCon.fileName, FileMode.Append, FileAccess.ReadWrite, store);
EditXML(isoStream, module, operation, xmlObj);
isoStream.Close();
}
}
#endregion
#region XML Creation And Editing
private static void CreateXML(StreamWriter sw, String mname, String operation, String xmlObj)
{
XmlWriter xWrt = XmlWriter.Create(sw);
xWrt.WriteStartElement("ocs");
// xWrt.WriteStartElement("module");
xWrt.WriteStartElement("operation");
xWrt.WriteAttributeString("mode", operation);
xWrt.WriteAttributeString("mname", mname);
xWrt.WriteRaw(xmlObj);
xWrt.WriteEndElement();
//xWrt.WriteEndElement();
xWrt.WriteEndElement();
xWrt.Close();
}
private static void EditXML(IsolatedStorageFileStream sw, String mname, String operation, String xmlObj)
{
sw.Seek(sw.Length - 6, SeekOrigin.Begin);
XmlWriterSettings wrSettings = new XmlWriterSettings();
wrSettings.OmitXmlDeclaration = true;
XmlWriter xWrt = XmlWriter.Create(sw,wrSettings);
//xWrt.WriteStartElement("module");
xWrt.WriteStartElement("operation");
xWrt.WriteAttributeString("mode", operation);
xWrt.WriteAttributeString("mname", mname);
xWrt.WriteRaw(xmlObj);
xWrt.WriteEndElement();
//xWrt.WriteEndElement();
xWrt.WriteRaw("</ocs>");
xWrt.Close();
}
You specify FileMode.Append here:
IsolatedStorageFileStream isoStream =
new IsolatedStorageFileStream(
IsolatedMemFileHandlingCon.fileName,
FileMode.Append,
FileAccess.ReadWrite, store);
Append does not combine with FileAccess.ReadWrite and with moving the cursor before the end of the file.
In the code you use random access, moving the cursor back:
sw.Seek(sw.Length - 6, SeekOrigin.Begin);
From the MSDN:
Append Opens the file if it exists and seeks to the end of the file,
or creates a new file. FileMode.Append can only be used in conjunction
with FileAccess.Write. Attempting to seek to a position before the end
of the file will throw an IOException and any attempt to read fails
and throws an NotSupportedException.

Resources