I use eclipse and put a File called "example.txt" into the bin-folder where the class files are generated (and into the sub-folder of the package). But still, the program allways prints out the error message i wrote for the case the file is not found.
Main Class:
import java.io.BufferedReader;
public class Main {
public static void main(String[] args){
BufferedReader file = Console.file("example.txt");
...
}
Console Class:
public final class Console {
public static BufferedReader file(String args) {
BufferedReader file = null;
try {
file = new BufferedReader(new FileReader(args));
} catch (FileNotFoundException e) {
println("Error, file not found!");
System.exit(1);
}
return file;
}
}
any ideas?
For the Eclipse project, the current path is the project folder, not the BIN directory, you can use the code below to get the current path so that you will know where to put and how to access the file.
import java.io.File;
import java.io.IOException;
public class MainTest {
public static void main(String[] args)
{
File directory = new File("");
try {
System.out.println(directory.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So in your case, the path you specify should be: ./bin/example.txt
Related
I'm quite new in OOP and Java programming, so please, forgive me.
I wrote a small class in which I try to write a String in a file using the BufferedReader class.
Everything works just fine, but the file is "empty", I mean that I can't see anything inside.
But for sure, data are stored, because when I close Eclipse and re open it again and run the driver class to make my tests, data are restored from the file.
By the way I use a "try with resources" mechanism so my file is "closed" automatically.
Does someone already meet this problem?
My Eclipse version is "2018-12"
Below, you have the small class with a "writeToFile" method in which I use the BufferedReader class.
package parlons.code.tipcalulator.utilities;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileManagement {
private File tipFile;
public FileManagement(String tipsFileName) {
this.tipFile = new File("/"+tipsFileName);
}
public String readFromFile() {
String tip = null;
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(this.tipFile))) {
tip = bufferedReader.readLine();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tip;
}
public void writeToFile(String decimal) {
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tipFile,true))){
bufferedWriter.write(decimal);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Below, you'll find the Driver class for testing purposes.
package parlons.code.tipcalulator.utilities;
public class UtilitiesTestDriver {
public static void main(String[] args) {
String decimal = "108";
FileManagement fileManagement = new FileManagement("tipFile.txt");
fileManagement.writeToFile(decimal);
System.out.println(fileManagement.readFromFile());
}
}
As per Makoto's comment above, everything works fine if you change to e.g.:
this.tipFile = new File("./"+tipsFileName);
This would create the tipFile.txt file (containing 108) in the root directory of your project (as opposed to the root of the filesystem - where you would probably not have write permission.)
I have a third-party library that requires the populating of a java File object at runtime. I have extended this code, but I do not need the file-related part. However, for my purposes, I am forced to create and use the File object and read from it.
Is there a way I can have the binary equivalent of an already-read file available at runtime? Or is there a way to have a file as byte-code already available for a File object? Please assume with my situation that going to a file-system to retrieve and open a file is not an option.
Thanks for any insights!
You can create a temp file and delete after your program finishes.
import java.io.*;
import java.nio.file.*;
public class Program {
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
String tmpDir = System.getProperty("java.io.tmpdir");
Path filePath = Paths.get(tmpDir, filename);
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
If you need a PHYSICAL file on they system, you can create it like so:
import java.io.*;
import java.nio.file.*;
public class Program {
public static final String TMP_DIR = System.getProperty("java.io.tmpdir");
public static final File EMPTY_FILE = createTmpFile("empty.dat");
private static final File createTmpFile(final String filename) {
Path filePath = null;
try {
byte[] data = { 0 }; // Write a single byte of data
filePath = Files.write(Paths.get(TMP_DIR, filename), data);
} catch (IOException e) {
e.printStackTrace();
}
return filePath.toFile();
}
public static void main(String[] args) {
try {
// Do stuff...
System.out.println(EMPTY_FILE.getCanonicalPath());
Thread.sleep(2000);
} catch (InterruptedException | IOException e) {
e.printStackTrace();
} finally {
// Cleanup...
EMPTY_FILE.delete();
}
}
}
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) {}
}
}
}
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?
import java.io.IOException;
public class Test1_Exec {
public static void main(String[] args) throws IOException {
Runtime run = Runtime.getRuntime();
try {
Process p = run.exec("java Test1");
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test1 {
public static void main(String[] args)
{
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream("d:\\ppp\\Test1.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("invoked successfully");
}
}
The problem is that if I run the Test1_Exec in the Eclipse, Test1.txt is not created and no error is reported. But if I type "java Test1" in the command window, Test1.txt is created. Test1_Exec.java and Test1.java are in the same src folder; Test1_Exec.class and Test1.class are in the same bin folder. So what's wrong with the Eclipse? My version of Eclipse is Kepler(20130614-0229).
Put bin folder in your classpath
Process p = run.exec("java -cp path/to/bin Test1");
Currently, java is looking for Test1.class inside your project directory.
Don't you need to give the full path for Test1 in the command?
i.e: "java c:\code\Test1" ?