copy Path in file writer Class into File Class - java

I would like to create a new file using filewriter class and use the exact path in file class (don't want to copy/paste the manually, any changes in file writer path, we would like to reflect the instances) to get absolute path of the particular file. Can anyone suggest me how?
First I would create a filewriter and later want to use File to display it's attributes such that any chnages in Fiewriter URL would be displayed.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class files_read {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
FileWriter FW=new FileWriter("C:/Users/91870/Downloads/Boss.txt");
FW.write("yoyo");
FW.close();
File f=new File(FW);
}
catch(IOException ie)
{
System.out.println("An error occurred.");
ie.printStackTrace();
}
}
}

You should do it the other way around. First create the File instance and then the FileWriter with that File instance.
File f = new File("C:/Users/91870/Downloads/Boss.txt");
FileWriter fw = new FileWriter(f);
...

Related

FileWriter only displays the last line

When I display the variable data using System.out.println(data), it displays the content (all lines) of the "filename.txt".
However, when I use myWriter.write(data), it only writes the last line of the initial file.
My task is to read a file (in this case, filename.txt) and copy its content into a new file (new.txt).
package javaapplication13;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class readFile {
public static String data;
public static void main(String[] args) throws IOException{
try{
File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\filename.txt");
try (Scanner myReader = new Scanner(myObj)) {
do{
data = myReader.nextLine();
}
while (myReader.hasNextLine());
PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
myWriter.write(data);
myWriter.close();
out.close();
myReader.close();
}
}
catch (FileNotFoundException e){
System.out.println("An error occurred.");
}
}
}
Every iteration of the loop opens a new writer, and then writes to it, thus overwriting the file. Instead, you should open the writer once, before the loop, and close it once you're done writing. E.g.:
try (FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt")) {
while (myReader.hasNextLine());
myWriter.write(myReader.nextLine());
}
}

Cannot resolve method 'openFile(java.lang.String)'

import java.io.File;
import java.util.Scanner
import java.io.FileNotFoundException;
public class hello {
public static void main (String [] args){
File file = new File("example.txt");
try {
openFile("example.txt");
} catch (FileNotFoundException exception){
System.out.println("Cannot find that file");
}
}
}
java : cannot find symbol
symbol : method openFile(java.lang.String)
Cannot resolve method 'openFile(java.lang.String)'
EDÄ°TED (thanks for our helps)
import java.io.File;
import java.io.FileNotFoundException;
public class hello {
public static void main(String [] args) {
try{
File file = new File("example.txt");
Scanner scanner = new Scanner(file);
System.out.println("opened");
}
catch (FileNotFoundException exception){
System.out.println("Cannot find that file");
}
}
}
Ok, I'm going to assume a few things here. Given that its a text file and you're trying to open it, I'm guessing you're trying to read it,if not then edit your question.
You need a bufferedReader, you can probably find an implementation for your specific case but the basics are:
create a buffered reader (called "reader" for example)
Use the following line:
reader = new BufferedReader(new FileReader(file));
Where file is the path to the .txt file.
Then to read do use
reader.readLine());
Put a while loop around this where the condition is that reader.readLine is not null
and also put a try/catch around it.
Hope this helps, I'm making a few assumptions but reading a .txt file is quite common and it looks like that's what you're trying to do.

How to use PrintWriter and File classes in Java?

I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
You should try creating a path for the folder it contains before:
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) throws IOException {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
throw an exception for the file.
Pass the File object to the constructor PrintWriter(File file):
PrintWriter printWriter = new PrintWriter(file);
import java.io.File;
import java.io.PrintWriter;
public class Testing
{
public static void main(String[] args)
{
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}
You should have a clear idea of exceptions in java.
In java there are checked exceptions and unchecked exceptions.
Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.
NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:
CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.
How to resolve:
1.Put your code in try catch block:
2.use throws keyword as shown by other guys above.
Advice:Read more about Exceptions.(I personally love this topic)
Java doesn't normally accept "/" to use in defining a file directory, so try this:
File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");
If the file doesn't exist do:
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own.
it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
import java.io.*;
public class test{
public static void main(Strings []args){
PrintWriter pw = new PrintWriter(new file("C:/Users/Me/Desktop/directory/file.txt"));
pw.println("hello");
pw.close
}
}
The PrintWriter class can actually create the file for you.
This example works in JDK 1.7+.
// This will create the file.txt in your working directory.
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter("file.txt", "UTF-8");
// The second parameter determines the encoding. It can be
// any valid encoding, but I used UTF-8 as an example.
} catch (FileNotFoundException | UnsupportedEncodingException error) {
error.printStackTrace();
}
printWriter.println("Write whatever you like in your file.txt");
// Make sure to close the printWriter object otherwise nothing
// will be written to your file.txt and it will be blank.
printWriter.close();
For a list of valid encodings, see the documentation.
Alternatively, you can just pass the file path to the PrintWriter class without declaring the encoding.
Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder.
If that does not work.
PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.
If you want to use PrintWrite then try this code
public class PrintWriter {
public static void main(String[] args) throws IOException {
java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
pw.println("hello world");
pw.flush();
pw.close();
}
}

Java How do I read and write an internal properties file?

I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");

How to create a file in a directory in java?

If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}

Categories