I am using a FileOutputStream to create a file in an activity that is not my MainActivity. The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity, the file cannot be found. What can I change in my code so that I don't get a fileNotFoundException? The relevant code is here:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
You used wrong way to read from an internal file, use the following code
try {
FileInputStream fis = context.openFileInput("file_name");
int content;
StringBuilder str = new StringBuilder();
while ((content = fis.read()) != -1)
str.append((char) content);
fis.close();
String savedText = str.toString();
} catch (IOException e) {
e.printStackTrace();
}
Related
I wrote an example of FileInputStream,But I found that if I use read() directly in the loop, there will be a problem with the printed data, and it cannot be displayed completely. After using the int variable to receive the return value of read(), it can be displayed normally here. Why?
code:
String path = "d:/hello.txt";
FileInputStream fileInputStream = null;
int readData = 0;
try {
fileInputStream = new FileInputStream(path);
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char) readData);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
This code is used to copy an instance through java serialization. It uses the traditional try-catch-finally writing method. Can it be changed to try-with-resources form?(The DeepConcretePrototype in the code is an ordinary java object)
/**
* Clone an instance through java serialization
* #return
*/
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
//Output an instance to memory
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
objectOutputStream.flush();
//Read instance from memory
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
clone = (DeepConcretePrototype)objectInputStream.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return clone;
}
Yes you can use try-with-resources, but it's a little tricky because the success of read depends on the success of write. One way you can write it is with a nested try:
public DeepConcretePrototype deepCloneBySerializable() {
DeepConcretePrototype clone = null;
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
//Output an instance to memory
objectOutputStream.writeObject(this);
objectOutputStream.flush();
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
//Read instance from memory
clone = (DeepConcretePrototype) objectInputStream.readObject();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return clone;
}
I create a client similarity, where clients register an account (an object is created) which is stored in a file.
Objects are written to the file as required, I override the writeStreamHeader() method. But when I try to read them all, their file throws an exception.
Write the objects to the file here.
public static void saveAccaunt(LoginAndPass gamers) {
boolean b = true;
FileInputStream fis = null;
try{
fis = new FileInputStream("student.ser");
fis.close();
}
catch (FileNotFoundException e)
{
b = false;
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream("student.ser",true);
ObjectOutputStream os = null;
if(b = true){
os = new AppendingObjectOutputStream(fileOutputStream);
System.out.println("Объект добавлен!");
}else {
os = new ObjectOutputStream(fileOutputStream);
System.out.println("Создан");
}
os.writeObject(gamers);
os.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("student.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
test = new ArrayList<>();
while (true){
test.add(objectInputStream.readObject());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(test.get(0));
}
Here is the error log for the exception thrown:
java.io.StreamCorruptedException: invalid stream header: 79737200
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
at java.io.ObjectInputStream.(ObjectInputStream.java:358)
at Registratsiya.AllGamers.main(AllGamers.java:48)
Exception in thread "main" java.lang.NullPointerException
at Registratsiya.AllGamers.main(AllGamers.java:61)
I am trying to save all my results from JSON into a text file. However, my for loop seems to be only saving the last result from the loop to the text file. It is obviously just re-writing the result each time into the file. I want to be able to save all the results from the for loop before it saves the file.
List<Status> statuses = null;
Query query = new Query("football");
query.setCount(100);
query.lang("en");
int i=0;
try {
QueryResult result = twitter.search(query);
ArrayList tweets = new ArrayList();
for( Status status : result.getTweets()){
System.out.println("#" + status.getUser().getScreenName() + ":" + status.getText());
String rawJSON = TwitterObjectFactory.getRawJSON(status);
String statusfile = "results.txt";
storeJSON(rawJSON, statusfile);
i++;
}
System.out.println(i);
}
catch(TwitterException e) {
System.out.println("Get timeline: " + e + " Status code: " + e.getStatusCode());
}
} catch (TwitterException e) {
if (e.getErrorCode() == 88) {
System.err.println("Rate Limit exceeded!!!!!!");
try {
long time = e.getRateLimitStatus().getSecondsUntilReset();
if (time > 0)
Thread.sleep(100);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream(fileName);
osw = new OutputStreamWriter(fos, "UTF-8");
bw = new BufferedWriter(osw);
bw.write(rawJSON);
bw.flush();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ignore) {
}
}
if (osw != null) {
try {
osw.close();
} catch (IOException ignore) {
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException ignore) {
}
}
}
}
}
The method at the bottom called storeJSON is where the work is being done.
Have you tried using a FileWriter with append mode ?
private static void storeJSON(String rawJSON, String fileName) throws IOException {
FileWriter fileWriter = null;
try
{
fileWriter = new FileWriter(fileName, true);
fileWriter.write(rawJSON);
fileWriter.write("\n");
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
} finally {
if(fileWriter!=null) {
fileWriter.close();
}
}
}
i want to know how to read and write text to a .txt file in j2me help me thanks...
public String readFile(String path)
{
InputStream is = null;
FileConnection fc = null;
String str = "";
try
{
fc = (FileConnection)Connector.open(path, Connector.READ_WRITE);
if(fc.exists())
{
int size = (int)fc.fileSize();
is= fc.openInputStream();
byte bytes[] = new byte[size];
is.read(bytes, 0, size);
str = new String(bytes, 0, size);
}
}
catch (IOException ioe)
{
Alert error = new Alert("Error", ioe.getMessage(), null, AlertType.INFO);
error.setTimeout(1212313123);
Display.getDisplay(main).setCurrent(error);}
finally
{
try
{
if (null != is)
is.close();
if (null != fc)
fc.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
return str;
}
void writeTextFile(String fName, String text)
{
OutputStream os = null;
FileConnection fconn = null;
try
{
fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if (!fconn.exists())
fconn.create();
os = fconn.openDataOutputStream();
os.write(text.getBytes());
fconn.setHidden(false);
// fconn.setReadable(true);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
if (null != os)
os.close();
if (null != fconn)
fconn.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}