FileNotFound exception error even thought the file exists in eclipse - java

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

Related

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.

What is wrong with my Java .html file generator

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

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 - How can I get the file paths of the contents of a given directory and write them to a text file?

I've found answers to various questions on here before, but this is my first time asking one. I'm kicking around an idea for my final project in my computer programming class, and I'm working on a few proof of concept programs in Java, working in Eclipse. I don't need anything more than to get the filepaths of the contents of a directory and write them to a .txt file. Thanks in advance!
Edit: I am posting my code below. I found a snippet of code to use for getting the contents and print them to the screen, but the print command is a placeholder that I'll replace with a write to folder command when I can.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ScanFolder {
public static void main(String[] args) throws IOException {
Files.walk(Paths.get("C:/Users/Joe/Desktop/test")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
}
EDIT: I've enclosed the OutputStreamWriter in a BufferedWriter
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("txt.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
writeContentsOfFileToAFile(new File("."), out, true); // change true to
// false if you
// don't want to
// recursively
// list the
// files
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void writeContentsOfFileToAFile(File parent, BufferedWriter out, boolean enterIntoDirectory) {
for (File file : parent.listFiles()) {
try {
out.write(file.toString() + "\r\n");
} catch (IOException e) {
e.printStackTrace();
}
if (enterIntoDirectory && file.isDirectory())
writeContentsOfFileToAFile(file, out, enterIntoDirectory);
}
}
Is this what you need?

Write Exceptions to File

The java project i have created is to be tested for 1800 cases and the output of each case has to matched with the golden(desired) output. I have created a perl script for this and running it on cygwin.
There are a few cases which throw exceptions but they are wrongly considered to be correct. I want to add a try catch block in java code so that if any exception is thrown it is caught and stack trace is printed on the file exception.txt.
Pseudo Java code:
main()
{
try
{
... //complete code of main()
}
catch (Exception e)
{
FileWriter fstream=new FileWriter("exception.txt");
BufferedWriter out=new BufferedWriter(fstream);
out.write(e.toString());
out.close();
}
}
But this overwrites the previous file contents and finally file contains the last thrown exception. How can i write catch block so that stackTrace is printed and contents of file are intact and not overwritten each time.
Use this constructor instead:
new FileWriter ("exception.txt", true);
It is described here.
EDIT: As per Jon's comment below:
If you want to print the entire stack trace, use printStackTrace:
fw = new FileWriter ("exception.txt", true);
pw = new PrintWriter (fw);
e.printStackTrace (pw);
Also, use the appropriate close calls after that.
You can use:
FileOutputStream fos = new FileOutputStream(new File("exception.txt"), true);
PrintStream ps = new PrintStream(fos);
e.printstacktrace(ps);
Here is a program that demonstrates what I think you need:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
public class StrackTraceAppender {
public static void main(String[] args) {
try {
thrower("Oh noes!");
} catch (Exception e) {
appendToFile(e);
}
try {
thrower("I died!");
} catch (Exception e) {
appendToFile(e);
}
}
public static void thrower(String message) throws Exception {
throw new RuntimeException(message);
}
public static void appendToFile(Exception e) {
try {
FileWriter fstream = new FileWriter("exception.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
PrintWriter pWriter = new PrintWriter(out, true);
e.printStackTrace(pWriter);
}
catch (Exception ie) {
throw new RuntimeException("Could not write Exception to file", ie);
}
}
}
It uses the printStackTrace(PrintWriter) method on Throwable to print the entire stack trace to the end of a file called "exception.txt", then there's a main() method which demonstrates usage with two sample exceptions. If you run it in your IDE, you should find that you get a file with two stack traces written to it (works for me).
Use
FileWriter fstream=new FileWriter("exception.txt", true);
to create an appending file writer.
Try this:
PrintStream printStream = new PrintStream(new File("exception.txt"));
try {
//error proven code
} catch (Exception exception) {
exception.printStackTrace(printStream);
}
Try this:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;
public class ErrorLogger
{
private Logger logger;
public ErrorLogger()
{
logger = Logger.getAnonymousLogger();
configure();
}
private void configure()
{
try
{
String logsFolder = "logs";
Files.createDirectories(Paths.get(logsFolder));
FileHandler fileHandler = new FileHandler(logsFolder + File.separator + getCurrentTimeString() + ".log");
logger.addHandler(fileHandler);
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
} catch (IOException exception)
{
exception.printStackTrace();
}
addCloseHandlersShutdownHook();
}
private void addCloseHandlersShutdownHook()
{
Runtime.getRuntime().addShutdownHook(new Thread(() ->
{
// Close all handlers to get rid of empty .LCK files
for (Handler handler : logger.getHandlers())
{
handler.close();
}
}));
}
private String getCurrentTimeString()
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
return dateFormat.format(new Date());
}
public void log(Exception exception)
{
logger.log(Level.SEVERE, "", exception);
}
}
Usage:
ErrorLogger errorLogger = new ErrorLogger();
try
{
throw new Exception("I died!");
} catch (Exception exception)
{
errorLogger.log(exception);
}

Categories

Resources