I'm starting with java, and now I'm doing some exercises on read/writing files.
I write strings with this format:
String wordList: word1 word2 word3; word4 word5 word6; code
Then I write this to the file using this code:
public void writeSelling(String wordList) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
write.writeObject(wordList);
write.close();
contador++;
}
But where I'm not getting able to do it right is when reading it. For now, what I get is a null when reading the content of the file, so I think that I'm doing something wrong on the method.
This is the method I use to read the file:
public ArrayList<Object> readSelling() throws Exception, FileNotFoundException, IOException {
ArrayList<Object> objectList = new ArrayList<Object>();
fileInPutStream = new FileInputStream (file);
read= new ObjectInputStream (fileInPutStream);
for (int i=0; i<contador; i++){
objectList.add(read.readObject());
}
read.close();
return objectList;
}
I call this method this way on the main file:
public static void listSelling(){
ArrayList objects;
try{
objects = sellingObject.readSelling();
for (Iterator it = sellingObject.iterator(); it.hasNext();) {
String s = (String)it.next();
System.out.println(s.toString());
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
I don't have knowledge enough to work with the Iterator, so maybe I'm not using it right.
UPDATE -- Definition of "file.dat
This file is defined this way in other class:
private final String file;
public WriteReadObject(String file){
this.file= file;
}
Then in the main file is called this way:
static WriteReadObject selling= new WriteReadObject("file.dat");
UPDATE 2 --
I see that when I'm writing to the file, I'm writing a null value, and here is where it fails.
I have this:
String one = word1 word2 word3
String two = word4 word5 word6
Before call the write method to write on the file, I add these 2 strings in another string to get only one string. To do this I've created this method:
public String add(String c, String m){
sellinglist[contador] = c + m;
contador++;
String list= sellinglist[contador];
return list;
}
Where c is string one and m y string two
alexey28 said the right thing - you're rewriting the file and finally there's only the last insertion. Anyway it's not that simple to just change FileOutputStream argument to make it work - you can't just append to an ObjectOuputStream - if you would like to, see here. It will corrupt the stream what will result in StreamCorruptedException.
The best solution would be to open ObjectOutputStream once at the begining, write all objects you want and then close stream.
Update
It all depends on how you receive data which are to be written (If you are writing strings then it would be probably more comfortable to do it not in binary mode but text - here is tutorial which explains how to do that).
If you want code how to simply write list of Strings then you can try this:
/* writing */
public void writeSelling(List<String> wordLists) throws IOException {
fileOutPutStream = new FileOutputStream (file);
write= new ObjectOutputStream (fileOutPutStream);
for (String s : wordLists) {
write.writeObject(s);
}
write.close();
contador++;
}
Now you can change code in the place where you call writeSelling().
/* calling method */
List<String> wordLists = new ArrayList<String>();
{ // it's probably loop
String wordList = // somehow receive list like word1 word2 word3; word4 word5 word6; code
wordLists.add(wordList);
}
writeSelling(wordLists);
The rest remains the same. Don't call writeSelling() method multiple times, just once.
The problem is you are writing single object and try to read an array of objects. Every time you are writing object you rewrite current file. Change openning of output stream to append data to file (but don't forget to clear it when writing first object):
fileOutPutStream = new FileOutputStream (file, contador != 0);
Related
Wrote a file in another class and now I'm trying to piece together the file into a JLabel, so I need to convert the name in the file into a string. Using FileReader and a char array to separate each character into an array to be put together in the JLabel.
I'm getting this error on NamePieces[x] = (char)nr;:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at clients.initialize(clients.java:197)
at clients.<init>(clients.java:72)
This is the code that I want to read the file:
try(FileReader nameReader = new FileReader(NamePath)) {
int nr = nameReader.read();
int x = 0;
while(nr != -1) {
namePieces[x] = (char)nr;
nr = nameReader.read();
x++;
}
}
catch (FileNotFoundException e) {}
catch (IOException e1) {}
String name = String.valueOf(namePieces[0]) + namePieces[1];
Doesn't work
Most likely, your problem occurs because namePieces is not initialized. As was already mentioned in the comments, you should not use char[] as a container for your characters (because in real world you won't know the length of the files' contents every time, so you will probably need to resize your container), it is way more better to use StringBuilder, provided by Java standard library. It will protect you from getting out of bounds.
StringBuilder namePieces = new StringBuilder();
File file = new File(filePath);
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(file),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
namePieces.append((char) c);
}
String nameString = namePieces.toString(); // Use this string as a complete array of needed characters
As you see I changed an approach by using not only StringBuilder, but also BufferedReader. However, for your task you can leave FileReader as it is. Just consider appending characters to builder.
If your file just contains a String there is a straightforward way to read it:
public String readMyFile( String fileName) throws IOException {
Path path = Paths.get(fileName);
return Files.readAllLines(path).get(0);
}
I have been trying to write an array to a file. I know how to write integers or String to a file but to bring an array confuses me. I am using this right now:
public static void write (String file, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write("hi");// Here I know i cant just write x[0] or anything. Do i need
//to loop in order to write the array?
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
You can use the ObjectOutputStream class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}
If the result is for humans to read and the elements of the array have a proper toString() defined...
outputString.write(Arrays.toString(array));
I have a Vehicle class which contains all information about Vehicle objects including get and set methods. There is also a Showroom class which maintains a list of all of the Vehicle objects, with methods to add/delete and scroll through the list.
In my main (a seperate class called VehicleDriverClass) I am trying to use I/O to write Vehicle data to a file and read in Vehicle data from a file. I can write to a file fine. I am using notepad and so a .txt file to read from. The problem I am having is with how to terminate the end of a line when reading from the file. Here is the constructor for the Vehicle class, so you know the paramaters.
public Vehicle(String man, String mod, String VIN, String dateOfMan, char taxBand, int costOfVehicle)
{
this.manufacturer = man;
this.model = mod;
this.VIN = VIN;
this.dateOfManufacture = dateOfMan;
this.taxBand = taxBand;
this.costOfVehicle = costOfVehicle;
}
This is what I have for the Input method at the moment (without trying to create the oject, just reading from file). The Showroom s being passed to it is for use later, when I create the vehicle object and add it to the showroom.
// code replaced below.
With this implementation when the dataFromFile is outputted to the console it is all on one line, rather than on new lines. Does readline() not terminate the line when '\n' is read in?
Here is how my data is stored in the input file.
Fordtest\n Focus\n frank\n ioCheck\n 09/01/1989\n 23/11/2013\n true\n d\n 1995\n
So for now, how do I get the line to terminate? So that I can then implement the creation of an object from this.
EDIT: I/O is working now. I am now having trouble with the constructor for my Vehicle object needing a the data types char and int for the last two variables. With the current method they are in a string array.
I have removed the code from above and added the new implementation below.public static void
addNewVehicleFromFile(Showroom s)
{
String dataFromFile;
String[] tokens = null;
try
{
File fileReader = new File("AddNewVehicleFromFile.txt");
FileReader fr = new FileReader(fileReader);
BufferedReader br = new BufferedReader(fr);
while ((dataFromFile = br.readLine()) != null)
{
tokens = dataFromFile.split("~");
}
System.out.println(Arrays.toString(tokens));
Vehicle inputVehicle = new Vehicle(tokens[0], tokens[1], tokens[2], tokens[3],
tokens[4], tokens[5]);
/*
Erorr above here with these two. token[4] should be a char and [5] an int
*/
s.addVehicle(inputVehicle);
System.out.println("addNewVehicleFromFile Complete");
}
catch (FileNotFoundException fnfe)
{
System.out.println("File not found exception: " + fnfe.toString());
}
catch (IOException ioe)
{
System.out.println("I/O exception: " + ioe.toString());
}
}
Should I be writing my own toChar and toInt methods to call for these two variables? Or parsing to int or similar.
I think you'll do better if you change your input data format. This is what XML and JSON were born for. If you must persist with your current arrangement, change the delimiter between data elements to something like a tilde '~' instead of \n.
So your input looks like this:
Fordtest~Focus~frank~ioCheck~09/01/1989~23/11/2013~true~d~1995
It's easy to parse now:
String [] tokens = data.split("~");
Write yourself some factory methods to create Vehicles:
public class VehicleFactory {
private static final VehicleFactory INSTANCE= new VehicleFactory();
private VehicleFactory() {}
public static VehicleFactory getInstance() { return INSTANCE; }
public static Vehicle createVehicle(String data) {
Vehicle value = null;
String [] tokens = data.split("~");
if ((tokens != null) && (tokens.length > X)) {
// Map String to int or Date here
value = new Vehicle(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]);
}
return value;
}
public static List<Vehicle> createVehicles(File f) {
List<Vehicle> values = new ArrayList<Vehicle>();
// implementation left for you
return values;
}
}
readLine() terminates the line when a character matching the Java syntax of \n is read. In most text editors, this is a newline. To express a newline in a Java string, use \n in the source code, but when creating the file by hand, use:
Fordtest
Focus
frank
ioCheck
09/01/1989
23/11/2013
true
d1995
I have been trying to write an array to a file. I know how to write integers or String to a file but to bring an array confuses me. I am using this right now:
public static void write (String file, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
outputWriter.write("hi");// Here I know i cant just write x[0] or anything. Do i need
//to loop in order to write the array?
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
}
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
You can use the ObjectOutputStream class to write objects to an underlying stream.
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
outputStream.writeObject(x);
And read the Object back like -
inputStream = new ObjectInputStream(new FileInputStream(filename));
x = (int[])inputStream.readObject()
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
Just loop over the elements in your array.
Ex:
for(int i=0; numOfElements > i; i++)
{
outputWriter.write(array[i]);
}
//finish up down here
private static void saveArrayToFile(String fileName, int[] array) throws IOException {
Files.write( // write to file
Paths.get(fileName), // get path from file
Collections.singleton(Arrays.toString(array)), // transform array to collection using singleton
Charset.forName("UTF-8") // formatting
);
}
If the result is for humans to read and the elements of the array have a proper toString() defined...
outputString.write(Arrays.toString(array));
So I'm learning new things day by day in Java, and I hope one day I should have same knowledge in Java as in PHP.
I'm trying to make a class that is similar to fopen, fwrite, fclose in PHP like:
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);
// the content of 'data.txt' is now 123 and not 23!
?>
I also need the method of writing
o - for delete and write/overwrite
a - for append at end
and a read function that returns the the content line by line, so I can put it into an array , like file_get_contents(file);
This is what I have so far ...
import java.io.*;
import java.util.Scanner;
/**
Read and write a file using an explicit encoding.
Removing the encoding from this code will simply cause the
system's default encoding to be used instead.
**/
public final class readwrite_txt
{
/** Requires two arguments - the file name, and the encoding to use. **/
public static void main(String[] args) throws IOException
{
String fileName = "text.txt";
String encoding = "UTF-8";
readwrite_txt test = new readwrite_txt(fileName,encoding);
test.write("argument.txt","some text","UTF-8","o");
}
/** Constructor. **/
readwrite_txt(String fileName, String encoding)
{
String fEncoding = "text.txt";
String fFileName = "UTF-8";
}
/** Write fixed content to the given file. **/
public void write(String fileName,String input,String encoding,String writeMethod) throws IOException
{
// Method overwrite
if(writeMethod == "o")
{
log("Writing to file named " + fileName + ". Encoding: " + encoding);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
try
{
out.write(input);
}
finally
{
out.close();
}
}
}
/** Read the contents of the given file. **/
public void read(String fileName,String output,String encoding,String outputMethod) throws IOException
{
log("Reading from file.");
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner = new Scanner(new FileInputStream(fileName), encoding);
try
{
while (scanner.hasNextLine())
{
text.append(scanner.nextLine() + NL);
}
}
finally
{
scanner.close();
}
log("Text read in: " + text);
}
// Why write System.out... when you can make a function like log("message"); simple!
private void log(String aMessage)
{
System.out.println(aMessage);
}
}
also, I don't understand why I must have
readwrite_txt test = new readwrite_txt(fileName,encoding);
instead of
readwrite_txt test = new readwrite_txt();
I just want to have an simple function similar to that in PHP.
EDITED
So my function must be
$fp = fopen('data.txt', 'w'); ==> readwrite_txt test = new readwrite_txt(filename,encoding,writeMethod);
fwrite($fp, '23'); ==> test.write("the text");
fclose($fp); ==> ???
to read a file in java you can
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) //Start of reading file
{
//what you want to do with every line is here
}
but for readwrite_txt test = new readwrite_txt(); problem ..
you must have another constructor inside the class that doesn't take any parameters
Have a look at the following file handling tutorials (Google is littered with them):
http://www.javapractices.com/topic/TopicAction.do?Id=42
http://www.coderanch.com/t/403914/java/java/do-read-entire-file-all
Pay attention to the following classes:
FileInputStream
FileOutpuStream
Scanner
There's all sorts of examples out there for you to learn from.
You can use the BufferedReader, here is an example and BufferedWriter, here is an example of write and here is an example for appending. For reading line-by-line you can use the readLine method of BufferedReader. You don't need those parameters in your constructor, because you don't use them, but you don't even need a class to implement these features because there are already standard classes for this purpose.
I hope this helps.