Java read a file, if it doesn't exist create it - java

here's my code
public String path;
public String fileName;
public static void readData() throws IOException{
try {
path="myPath"
fileName="myFileName";
fstream = new FileInputStream(path+fileName);
br = new BufferedReader(new InputStreamReader(fstream));
//do something...//
}
br.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Reading file error");
Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
I wanted to know how to check if the fstream exists. If it doesn't exist, a new file has to be created. How can I do this?
Thanks

Here's a possible solution:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile())
{
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try
{
// read data
}finally
{
r.close();
}
}

Something's missing in your code - there's a closing brace with no corresponding opening brace.
But to answer your question, create a File object first and use exists(), then createNewFile() if exists() returns false. Pass the File object instead of the filename to the FileInputStream constructor.
BTW, it would have taken you less time to google the answer than it did to type in your question here.

To check if the file filename exists in path, you can use new File(path, filename).exists().
The exists method returns true if a file or directory exists on the filesystem for the specified File.
To verify that the file is a file and not a directory, you can use the isFile method.
See the javadoc for java.io.File for more information.

if(new File("filename").exists())
...
it should do what you want.

You are already catching FileNotFoundException and this is the very place where you know that the file you wanted to read doesn't exist and you can create it.

Related

BufferedReader/FileReader is not finding path correctly even with try/catch

I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.

What is the simplest way to write a text file in Java?

I am wondering what is the easiest (and simplest) way to write a text file in Java. Please be simple, because I am a beginner :D
I searched the web and found this code, but I understand 50% of it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
With Java 7 and up, a one liner using Files:
String text = "Text to save to file";
Files.write(Paths.get("./fileName.txt"), text.getBytes());
You could do this by using JAVA 7 new File API.
code sample:
`
public class FileWriter7 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList(new String[] { "This is the content to write into file" });
String filepath = "C:/Users/Geroge/SkyDrive/Documents/inputFile.txt";
writeSmallTextFile(lines, filepath);
}
private static void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
Path path = Paths.get(aFileName);
Files.write(path, aLines, StandardCharsets.UTF_8);
}
}
`
You can use FileUtils from Apache Commons:
import org.apache.commons.io.FileUtils;
final File file = new File("test.txt");
FileUtils.writeStringToFile(file, "your content", StandardCharsets.UTF_8);
Appending the file FileWriter(String fileName,
boolean append)
try { // this is for monitoring runtime Exception within the block
String content = "This is the content to write into file"; // content to write into the file
File file = new File("C:/Users/Geroge/SkyDrive/Documents/inputFile.txt"); // here file not created here
// if file doesnt exists, then create it
if (!file.exists()) { // checks whether the file is Exist or not
file.createNewFile(); // here if file not exist new file created
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // creating fileWriter object with the file
BufferedWriter bw = new BufferedWriter(fw); // creating bufferWriter which is used to write the content into the file
bw.write(content); // write method is used to write the given content into the file
bw.close(); // Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.
System.out.println("Done");
} catch (IOException e) { // if any exception occurs it will catch
e.printStackTrace();
}
Your code is the simplest. But, i always try to optimize the code further. Here is a sample.
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("./output/output.txt")))) {
bw.write("Hello, This is a test message");
bw.close();
}catch (FileNotFoundException ex) {
System.out.println(ex.toString());
}
Files.write() the simple solution as #Dilip Kumar said. I used to use that way untill I faced an issue, can not affect line separator (Unix/Windows) CR LF.
So now I use a Java 8 stream file writing way, what allows me to manipulate the content on the fly. :)
List<String> lines = Arrays.asList(new String[] { "line1", "line2" });
Path path = Paths.get(fullFileName);
try (BufferedWriter writer = Files.newBufferedWriter(path)) {
writer.write(lines.stream()
.reduce((sum,currLine) -> sum + "\n" + currLine)
.get());
}
In this way, I can specify the line separator or I can do any kind of magic like TRIM, Uppercase, filtering etc.
String content = "your content here";
Path path = Paths.get("/data/output.txt");
if(!Files.exists(path)){
Files.createFile(path);
}
BufferedWriter writer = Files.newBufferedWriter(path);
writer.write(content);
In Java 11 or Later, writeString can be used from java.nio.file.Files,
String content = "This is my content";
String fileName = "myFile.txt";
Files.writeString(Paths.get(fileName), content);
With Options:
Files.writeString(Paths.get(fileName), content, StandardOpenOption.CREATE)
More documentation about the java.nio.file.Files and StandardOpenOption
File file = new File("path/file.name");
IOUtils.write("content", new FileOutputStream(file));
IOUtils also can be used to write/read files easily with java 8.

File not found exception that does not make sense (For me)

I have a program that reads and writes from a file. I EVEN tried to create the file in main but it still doesn't work.
public static void main(String[] args) throws NumberFormatException,
IOException,
FileNotFoundException {
System.out.println("Work in progress");
File f = new File("Data.txt");
System.out.println(f.getAbsolutePath());
// Yes, it's there.
UI ui = new UI();
GenericDictionary<Integer> gd = new GenericDictionary<Integer>();
Repository repo = new Repository("Data.txt", gd);
// Should work, right ?
Now my Repository:
public Repository (String fileName, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException {
this.fileName = fileName;
this.gd = gd;
FileReader input = null;
BufferedReader inputBuffer = null;
try {
input = new FileReader(this.fileName);
inputBuffer = new BufferedReader (input);
String line;
while ((line = inputBuffer.readLine()) != null) {
String[] inputData = line.split(",");
Node<Integer> newNode = new Node<Integer> (
Integer.parseInt(inputData[0]),
Integer.parseInt(inputData[1]));
this.gd.add(newNode);
}
}catch (NumberFormatException nfe){
System.out.println(
"Repository could not load data due to NumberFormatException: "
+ nfe);
}catch (FileNotFoundException fnfe) {
System.out.println("File not found, error: " + fnfe);
}finally {
inputBuffer.close();
input.close();
}
}
Now even though I create my file it does not want to use it. Initially it was in the constructor of my repository, I moved it into the main file, still no success.
This is what Eclipse prints within console:
Work in progress
D:\Info\Java workspace\Laborator_4\Data.txt
File not found, error: java.io.FileNotFoundException: Data.txt (The system cannot find the file specified)
Exception in thread "main" java.lang.NullPointerException
at repository.Repository.(Repository.java:49)
at main.app.main(app.java:23)
This doesn't do what you think it does:
File f = new File("Data.txt");
System.out.println(f.getAbsolutePath());
// Yes, it's there.
That doesn't create a file on disk. It just creates a File object representing a path name. If you use:
System.out.println(f.exists());
that will show you whether or not it really exists.
So unless D:\Info\Java workspace\Laborator_4\Data.txt really, really exists, it's entirely reasonable for you to get an exception. Create the file and try again.
Additionally, you're getting a NullPointerException in your finally block because you're assuming that inputBuffer and input are both non-null: don't make that assumption. Check before closing.
A File is an abstract path. Executing this:
File f = new File("Data.txt");
Does absolutley nothing on disk. Nor is this
System.out.println(f.getAbsolutePath());
Any test for existence of the file.
Do this:
if(file.exists()) {
// yes it's there
}
As others Stated you don't create a file, try touch() method from here: ApacheFileUtils
I hope this works :
Replace this line
Repository repo = new Repository("Data.txt", gd);
with :
Repository repo = new Repository(f, gd);
and in your
public Repository (String fileName, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException
use this
public Repository (File f, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException
and in try { }
instead of
input = new FileReader(this.fileName);
do this
input = new FileReader(f.getAbsolutePath());

Writing from System.out.println to a file

I've replaced many strings and outputted the result and now am trying to write those lines into a text file. Here's what I did. I created a new file:
File newfile = new File("/Users/Bill/Desktop/newfile.txt");
if (newfile.exists()) {
System.out.println("File exists");
} else {
newfile.createNewFile();
System.out.println("New file created");
}
And then I tried to write to the created file the result of System.out.println(lines[i]);
try {
WriteToFile newFile = new WriteToFile(newfile, true);
newFile.write(lines[i]);
// lines[i] is what I used to print out System.out.println(lines[i])
}
catch (IOException e) {
System.out.println("Error.");
}
I'm not getting what I'm expecting, though. Any suggestions?
WRITETOFILE:
public class WriteToFile {
private String path;
private boolean append = false;
public WriteToFile(String filename) {
path=filename;
}
public WriteToFile(String filename, boolean appendfile){
path=filename;
append=appendfile;
}
public void write(String text) throws IOException {
FileWriter filewrite = new FileWriter(path, append);
PrintWriter print = new PrintWriter(filewrite);
print.printf("%s" + "%n", text);
print.close();
}
}
Every time you call WriteToFile.write, it reopens the file for writing, truncating the file's original contents. You should open the file once, in the constructor (and store the PrintWriter in a field), and add a close method that calls close for the PrintWriter.
On the calling side, do this:
WriteToFile writer = new WriteToFile(filename);
try {
// writer.write(...);
} finally {
writer.close();
}
By having the close call in a finally block, you ensure the file is closed even if an exception causes the function to quit early.
Look at the 2nd argument of the FileWriter constructor in your code.
FileWriter filewrite = new FileWriter(path, append);
See, it says "append". Guess what it does. Read the documentation if you're unsure.
Now, look how you initialized append.
private boolean append = false;
This code is fully behaving as expected. It's just a developer's fault. Fix it :)
Just set fileName on System using the method
System.setOut(fileName);
Then whenever we want to print using System.out.println() it will directly print to the fileName you mention.

Test if file exists

I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.

Categories