What is wrong with my Java .html file generator - java

I am working on an .html file generator that can be used to view .swf files in a browser, however I'm getting a "Unresolved compilation problem" error. Is there possibly a problem with my imports?
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class CreateFile {
public static String starthtml = "<object><embed src=\"";
public static String endhtml = ".swf\" width=\"100%\" height=\"100%\"></embed></object>";
public static String s;
public static void main(String[] args) {
try {
File myObj = new File("Flash Loader.html");
if (myObj.createNewFile()) {
System.out.println("Flash Loader Created Successfully");
} else {
System.out.println("File already exists");
}
} catch (IOException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter SWF file name");
s = sc.nextLine();
try {
FileWriter myWriter = new FileWriter("Flash Loader.html");
myWriter.write(starthtml+sc+endhtml);
myWriter.close();
System.out.println("Successfully wrote to the file");
} catch (IOException e) {
System.out.println("An error occurred");
e.printStackTrace();
}
}
}
Error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at CreateFile.main(Flash_Loader_Creator.java:10)

Renaming my .java file to CreateFile.java fixed the issue thank you https://stackoverflow.com/users/1081110/dawood-says-reinstate-monica
https://stackoverflow.com/users/1902512/haibrayn-gonz%c3%a1lez

Related

resource leak and output file is not writing

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.

I can't write on multiple lines in a txt file in java

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.

FileNotFound exception error even thought the file exists in eclipse

While running my java file io program I'm getting FileNotFoundException
I tried changing the directory of the file and most of the other solution mentioned in SO, nothing works.
My code:
package com.HelloWorld;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) {
FileWriter w=null;
BufferedWriter bw=null;
try {
String s="welcome";
String b="‪‪D:\\test.txt";
w=new FileWriter(b);
bw=new BufferedWriter(w);
bw.write(s);
bw.flush();
}
catch(IOException e)
{
System.out.println("exception caught"+e);
}
finally{
try {
if(bw!=null)
bw.close();}
catch(Exception e) {
System.out.println("exception caught"+e);
}
try {
if(w!=null)
{
w.close();
System.out.println("success");
}}
catch(Exception e) {
System.out.println("exception caught"+e);
}
}
}
}
I had already created the file in the D drive so the FileWriter overrides the already created file name because of which it did not write to the file

FileOutputStream doesn't show FileNotFoundException

for FileOutputStream, it will throw a FileNotFoundException if the file doesn't exist, but it will create it if it can.
I dont have a Sample.txt in my project root
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
try {
FileOutputStream s= new FileOutputStream("Sample.txt");
} catch (FileNotFoundException e) {
System.out.println("File not Found");
}
}
}
The problem is:
I cannot see the Output of the "File Not Found" from the Terminal. How did it happen?
Thank you
You can set Sample.txt as a File first and check if it exists with .canWrite()
You still have to put a try/catch around FileOutputStream, but it should never go in the catch block.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class test {
public static void main(String[] args) {
File f = new File("Sample.txt");
if (!f.exists()) {
System.out.println("File not Found");
}
else {
try {
FileOutputStream s = new FileOutputStream(f);
} catch (FileNotFoundException e) {}
}
}
}

Java write to .csv file

I am trying to write to a .csv file, but I keep getting the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
void is an invalid type for the variable writeToFile
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
The error is associated with the line:
void writeToFile(String Filename){
Here is my code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileWriter;
public class writeFileExample {
public static void main(String[] args) {
void writeToFile(String Filename){
double steps=0;
File file=new File(Filename);
file.createNewFile();
FileWriter writer=new FileWriter(file);
try {
//Integrate integrate=new Integrate();
//for (steps=10;steps<1000000;steps=steps*10){
//double area_value=integrate.integrate_function(steps);
writer.write("Steps"+","+"Area");
//}
//System.out.println(area_value);
writer.flush();
writer.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
I can't see any syntax errors.
Taking into account Reimeus' comment below I edited it a bit. I now have:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileWriter;
void writeToFile(String Filename){
public class writeFileExample {
public static void main(String[] args) {
double steps=0;
etc.
I am getting the error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Filename cannot be resolved to a variable
Any help appreciated.
Java doesnt support nested methods. Move writeToFile out of the main method
public class Test {
public static void main(String[] args) {
try {
writeToFile("c:\\abc.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static public void writeToFile(String Filename) throws IOException
{
.
.
.
.
}
}

Categories

Resources