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.
Related
I get a resource leak warning in return new ArrayList<>();. The file is not writing in the friends.txt which I am trying to save list in a text file. Please help.
import java.io.*;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
FileOutputStream friendFile;
ObjectOutputStream friendWriter;
try {
friendFile = new FileOutputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendWriter = new ObjectOutputStream(friendFile);
if(friends.size() >0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
friendWriter.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (IOException e) {
System.out.println("Stream cannot be initialized.");
}
}
public ArrayList<Friend> readFriends() {
FileInputStream friendFile;
ObjectInputStream friendReader;
ArrayList<Friend> friends = new ArrayList<>();
try {
friendFile = new FileInputStream(new File("C:\\Users\\aa\\Desktop\\src\\friends.txt"));
friendReader = new ObjectInputStream(friendFile);
int size = friendReader.readInt();
if(size > 0){
for (int i = 0; i < friendReader.readInt(); i++) {
friends.add((Friend) friendReader.readObject());
}
}
else{
System.out.println("Empty File");
return new ArrayList<>();
}
friendReader.close();
friendFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'Friends.txt'");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("Stream cannot be inititalized");
}
return friends;
}
}
I am trying to save a list of friends in the friends.txt file. I see no output in the friends.txt file. Is it something to do with my location or FileOutputStream ?
You have two problems in your code.
There is a bug in the for loop in method readFriends of class ReadWrite.
The file friends.txt may not be closed.
Here is the corrected code. Note that I could not find the code for class Friend in your question so I wrote a minimal class. Since you are using serialization, I assume that class Friend implements interface Serializable.
Notes after the code.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class ReadWrite {
public void writeFriends(ArrayList<Friend> friends) {
try (OutputStream friendFile = Files.newOutputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectOutputStream friendWriter = new ObjectOutputStream(friendFile)) {
if (friends.size() > 0) {
friendWriter.writeInt(friends.size());
for (Friend friend : friends) {
friendWriter.writeObject(friend);
}
}
else {
System.out.println("No data to write");
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be initialized.");
e.printStackTrace();
}
}
public ArrayList<Friend> readFriends() {
ArrayList<Friend> friends = new ArrayList<>();
try (InputStream friendFile = Files.newInputStream(Paths.get("C:", "Users", "aa", "Desktop", "src", "friends.dat"));
ObjectInputStream friendReader = new ObjectInputStream(friendFile)) {
int size = friendReader.readInt();
if (size > 0) {
for (int i = 0; i < size; i++) {
friends.add((Friend) friendReader.readObject());
}
}
else {
System.out.println("Empty File");
return new ArrayList<>();
}
}
catch (FileNotFoundException e) {
System.out.println("File Not Found. Retry after creating File 'friends.dat'");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
System.out.println("Stream cannot be inititalized");
e.printStackTrace();
}
return friends;
}
public static void main(String[] args) {
ArrayList<Friend> friends = new ArrayList<>();
Friend friend = new Friend("Jane");
friends.add(friend);
ReadWrite rw = new ReadWrite();
rw.writeFriends(friends);
ArrayList<Friend> newFriends = rw.readFriends();
System.out.println(newFriends);
}
}
class Friend implements Serializable {
private String name;
public Friend(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
In the for loop condition in method readFriends you have the following:
friendReader.readInt()
This means that in every loop iteration, you are trying to read another int from the file friends.txt. This call fails since there is only one int in the file. Hence you need to use size which is the variable that contains the only int in file friends.txt which you read before the for loop.
Since you are using serialization, it is recommended to give the file name an extension of .dat rather than .txt since the file is not a text file.
I always write printStackTrace() in my catch blocks since that helps me to locate the cause of the exception. You actually should not get a FileNotFoundException since Java will create the file if it doesn't exist. If Java fails to create the file, then it is probably because the user has no permission to create a file, so displaying an error message saying to create the file before running your code probably won't help.
Your code may successfully open the file and write some data to it and crash before you have written all the data. In that case, your code does not close the file. If you are using at least Java 7, then you should use try-with-resources to ensure that the files are always closed.
Java 7 also introduced NIO.2 as a better API for interacting with the computer's file system from Java code. I suggest that you use it as I have shown in the code, above.
So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
public static void main( String args[]) {
int a = 32;
int b=12;
int c=33;
List<Integer> myList = new ArrayList();
myList.add(a);
myList.add(b);
myList.add(c);
/* for(int s:myList)
{
System.out.println(s);
}
*/
//Om ar= new Om("Alex",21,185);
//System.out.println(ar);
try{
File myObj = new File("filename.txt");
if(myObj.createNewFile()){
System.out.println("File created " + myObj.getName());
}
else
{
System.out.println("File already exists");
}
}
catch (IOException e)
{
System.out.println("An error has occurred");
e.printStackTrace();
}
try {
FileWriter myWriter = new FileWriter("filename.txt");
for(int i=1;i<10;i++)
{
myWriter.append("This is a new file, nothing sus here."+i + " ");
}
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.
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");
}
I have written the code bellow to check if a properties file exists and has the required properties. If it exists it prints the message that the file exists and is intact, if not then it creates the properties file with the required properties.
What I wanted to know is, is there a more elegant way of doing this or is my way pretty much the best way? Also the minor problem that I'm having is that with this way it doesn't check for extra properties that should not be there, is there a way to do that?
Summary of my requirements:
Check if the file exists
Check if it has the required properties
Check if it has extra properties
Create the file with the required properties if it doesn't exist or if there are extra or missing properties
Source files and Netbeans Project download
Source:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
public class TestClass {
public static void main(String[] args) {
File propertiesFile = new File("config.properties");
if (propertiesFile.exists() && propertiesExist(propertiesFile)) {
System.out.println("Properties file was found and is intact");
} else {
System.out.println("Properties file is being created");
createProperties(propertiesFile);
System.out.println("Properties was created!");
}
}
public static boolean propertiesExist(File propertiesFile) {
Properties prop = new Properties();
InputStream input = null;
boolean exists = false;
try {
input = new FileInputStream(propertiesFile);
prop.load(input);
exists = prop.getProperty("user") != null
&& prop.getProperty("pass") != null;
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return exists;
}
public static void createProperties(File propertiesFile)
{
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(propertiesFile);
prop.setProperty("user", "username");
prop.setProperty("pass", "password");
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
this is my way. (not sure if more elegant, but it can be an inspiration/different aproach)
Try/catch should be enough to see if the file exists or not
try {
loading files etc...
} catch (FileNotFoundException e) {
throw new MojoExecutionException( "[ERROR] File not found", e );
} catch (IOException e) {
throw new MojoExecutionException( "[ERROR] Error reading properties", e );
}
Code that checks your loaded prop:
Properties tmp = new Properties();
for(String key : prop.stringPropertyNames()) {
if(tmp.containsKey(key)){
whatever you want to do...
}
}
I use tmp, a new properties variable, to compare with ,but the key variable will hold a string so in the if statement you can compare it to array of strings and the way you do it is up to you.
I'm trying to read ObjectOutputStream from a file and convert it to an arraylist.
This whole thing is happening inside a method which should read the file and return the array list:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java tells me that this is dangerous.
What are the alternatives?
I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.
I need to both make sure files will be closed, and return the array list I created as well.
Any ideas?
I can't put the return in the "try" block because it won't do it / it
won't close files in the "finally" block.
Wrong, finally block would still execute if you put return in try block. Thus you can return in your try block.
try
{
//your code
return buildingsArr;
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
}
I would suggest starting to use Java 7, and the try with resources clause. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Ex:
static String readFirstLineFromFile(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
}
You must either throw an Exception or return a value:
All you need to prove this is comment out the return "File Not Found" after the finally block and see that it won't compile.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReturnFinallyExample
{
public static void main(final String[] args)
{
returnFinally();
}
private static String returnFinally()
{
try
{
final File f = new File("that_does_not_exist!");
final FileInputStream fis = new FileInputStream(f);
return "File Found!";
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
System.out.println("finally!");
}
return "File Not Found!";
}
}
You must have the return after the finally or you have to either:
declare the method to throws FileNotFoundExceptoin and re-throw the FileNotException out.
or
wrap the FileNotFoundException with throw new RuntimeException(e)