This question already has answers here:
How can I quickly load a large txt file into BigInteger?
(3 answers)
Closed 5 years ago.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// Load file with 17 million digit long number
BufferedReader Br = new BufferedReader (new FileReader("test2.txt"));
String Line = Br.readLine();
try {
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write the number into a new file
oout.writeObject(Line);
// close the stream
oout.close();
// create an ObjectInputStream for the new file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
// convert new file into a BigInteger
BigInteger Big = (BigInteger) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is a program I made for learning how to use Input/OutputStream. Everything works except that I get an error when trying to turn my file into a BigInteger.
java.lang.String cannot be cast to java.math.BigInteger
at ReadOutPutStream.main
I'm new to this so I'm probably making a simple error, what am I doing wrong?
You wrote a string to the file with
oout.writeObject(Line);
Therefore when you read an object from the stream it will also be a String. You can't cast a String to a BigInteger so you get an exception. I know form your earlier question that you want to serialize the BigInteger to save time when deserializing from the filesystem, so to fix your specific problem you should write a BigInteger to the stream instead of a string:
oout.writeObject(new BigInteger(Line));
Related
I need to read a binary file and save each byte into a byte array. I've read other stackoverflow posts on this topic, but cannot figure out why mine does not work. Here is what I have:
String fileOne = "file1.bin";
byte[] byteArray = new byte[1000];
try{
FileInputStream fileIS = new FileInputStream(fileOne);
ObjectInputStream is = new ObjectInputStream(fileIS);
is.read(byteArray);
is.close();
for(int i =0; i < byteArray.length; i++){
System.out.println(byteArray[i]);
}
}
catch (FileNotFoundException e){
e.toString();
System.exit(0);
}
catch (IOException io){
io.toString();
System.exit(0);
}
Here's a way to read the contents of a file into a byte array. FileInputStream is all you need – leave ObjectInputStream out of it (unless you are explicitly dealing with data that was created from an ObjectOutputStream, but that doesn't seem to be the case since you are calling println() on each byte).
public static void main(String[] args) {
String filename = "file1.bin";
try (FileInputStream fis = new FileInputStream(filename)) {
byte[] bytes = fis.readAllBytes();
for (byte b : bytes) {
System.out.print(b);
}
} catch (Exception e) {
e.printStackTrace();
}
}
A few things here:
omit using ObjectInputStream – not needed for reading byte data, and won't work unless the data was created by the corresponding output stream. From the Javadoc: "An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. "
use try with resources – it will close the associated stream for you
catch Exception – in the code you posted, you will only see info if FileNotFoundException or IOException is thrown. For anything else, your code doesn't handle them or print out any info.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a method that writes integer array into a file.
When I read it with a method that brings those ints as array it's working.
But when I try to count how many ints it says it's empty.
The same code is written on other computer systems. and it's working for him, the SAME code!
I already put the "buffer" byte array into the read method. still not working
File file = new File("/home/arad/Desktop/intFile.bin");
int[] arr = {1,2,3,4,5,6};
//exampleWriteIntegerArray(arr, file);
reverseThisFile(file);
static void reverseThisFile(File file){
File newFile = new File("/home/arad/Desktop/newIntegerFile.bin");
InputStream inputStream = null;
OutputStream outputStream = null;
int counter = 0;
System.out.println(file.length());
try {
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
byte[] buffer = new byte[4];
int actuallyRead;
while((actuallyRead = inputStream.read()) != -1){
counter++;``
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println(counter);
}
Is something wrong in lines (input and output files are same):
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file); //comment this line
Name your variables better (outputFile, inputFile)... Also output stream outputStream is not closed... Try first just to print on console, ...
he uses Windows i use Ubuntu
I suspect this is the root of the difference, in conjunction with this code:
inputStream = new FileInputStream(file);
outputStream = new FileOutputStream(file);
In the first line, you're opening the existing file to read it. In the second line, you're creating a new, empty file. Should inputStream read from that empty file, or from the file that existed before you created the new one? I believe that the behaviour of Windows and Linux (and their file systems) may differ there.
I would strongly suggest that you don't do that.
Two alternative options:
Use two different files. Read from one, write to the other.
Do all the reading first, then do all the writing.
In both of these options, you never have an input and output stream to the same file at the same time... it's that part that's the recipe for problems.
This question already has answers here:
How to binary (de)serialize object into/form string?
(2 answers)
Closed 5 years ago.
Object before = "";
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(os);
oo.writeObject(before);
oo.close();
String serialized = os.toString("UTF-8");
ByteArrayInputStream is = new ByteArrayInputStream(serialized.getBytes("UTF-8"));
try(ObjectInputStream io = new ObjectInputStream(is)) {
Object after = io.readObject();
System.err.println("Object deserialization successful.");
} catch (Exception e) {
System.err.println("Object deserialization error.");
System.err.println("Type being serialized: " + before.getClass());
System.err.println("Serialization as bytes: " + Arrays.toString(serialized.getBytes("UTF-8")));
e.printStackTrace();
}
So I've got a bit of code I'm working with that's supposed to serialize an object to a java.lang.String and deserialize it later. I'm using object streams to do the object writing/reading and byte array streams to do the string handling. But when I try to construct an ObjectInputStream around the serialized object, I get a StreamCorruptedException, claiming there's an "invalid stream header".
The code sample above is the most basic piece of code I could find that reproduces my issue (and it's pretty simple!). As far as I can tell, I'm doing everything perfectly symmetrically:
Make an ObjectOutputStream around a ByteArrayOutputStream
Write a (simple!) object to the OOS
Get a UTF-8 String from the BAOS
Make an ObjectInputStream around a ByteArrayInputStream around that String's UTF-8 bytes
Read an object from the OIS
But at step 4, during ObjectInputStream's constructor the program crashes with a StreamCorruptedException. I'm extremely confused by that, given that the bytes were literally just produced by an ObjectOutputStream!
Don't convert the byte[] to and from a String, that is going to interpret special (wide) characters. Instead, just use the bytes from the ByteArrayOutputStream directly. Like,
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 9 years ago.
I am taking a number of inputs from the user like Name,age,e-mail etc.. , and I concatenated all these fields with a ":" delimiter
`String line = Anjan+":"+21+":"+abc#abcd.com;`
My question is:
How do I write the String line into a file?
I repeat the process of taking inputs from users. Can somebody explain me, how can I write the line to a file each time, after I am done with reading and concatenating the inputs?
If you are using java 7 it will be quite easy,
public void writerToPath(String content, Path path) throws IOException {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)))){
writer.newLine();
writer.write(content);
}
}
Since Writer implements the AutoClosable interface will the writer and underlying streams be closed when finished or if an exception occur.
public static void write(final String content, final String path)
throws IOException {
final FileOutputStream fos = new FileOutputStream(path);
fos.write(content.getBytes());
fos.close();
}
Try the following code. You can create method and pass values as parameter. It'll append the new line every time. It won't remove existing lines(data)
File logFile = new File( System.getProperty("user.home") + File.separator + "test.txt");
String data = "value";
if(!logFile.exists()){
logFile.createNewFile();
}
FileWriter fstream = new FileWriter(logFile.getAbsolutePath(),true);
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(data);
fbw.newLine();
fbw.close();
I am trying to read 2 arraylists using the following methods.
public static ArrayList<Contestant> readContestantsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject();
ois.close();
return contestants;
}
public static ArrayList<Times> readContestantsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<times> times = (ArrayList<Times>) ois.readObject();
ois.close();
return times;
}
Bit this doesn't work. It cannot cast to the the second arraylist type i've saved. So how can I access this? The exact error I got was this:
Exception in thread "main" java.lang.ClassCastException: com.deanchester.minos.model.Contestant cannot be cast to com.deanchester.minos.model.Times
at com.deanchester.minos.tests.testAddTime.main(testAddTime.java:31)
The line that this is referring to is:
ArrayList<times> times = (ArrayList<Times>) ois.readObject();
So how can I read 2 different arraylists from one file?
Use FileOutputStream fos = new FileOutputStream("minos.dat", true); when writing the second file. true is a value of argument "append". Otherwise you override the file content. This is the reason that you read the same collection twice.
When you are reading the second collection from the file you have to skip to the beginning of the second collection. To do this you can remember how many bytes have you read on first phase and then use method skip().
But better solution is to open file only once (I mean call new FileInputStream and new FileOutputStream) only once and then pass it to methods that read collections.
You can read two different objects from a file using a ObjectInputStream, but your problem comes from the fact that you reopen the stream so it starts at the beginning of the file where you have the ArrayList<Contestant> and then you ArrayList<Times>. Try doing everything at once and returning both lists:
public static ContestantsAndTimes readObjectsFromFile() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("minos.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Contestant> contestants = (ArrayList<Contestant>) ois.readObject();
ArrayList<Times> times = (ArrayList<Times>) ois.readObject();
ois.close();
return new ContestantsAndTimes(contestants, times);
}