I'm trying to make a small program that allows to create a 'txt' file. My teacher taught me to use BufferedReader and PrintWriter but I don't know how to allow the user to choose the path (you know, like when you save something on a software).
Thanx for your answer.
(Sorry for my english, not my native language)
You can input it with a Scanner, and then append the file name to it using Path#get:
System.out.println("Please enter the target directory: ");
Scanner in = new Scanner(System.in);
String dir = in.next();
String filePath = Paths.get(dir, "myfile.txt").toString();
// Go on and create the file as you would normally do
I assume you want to use BufferedReader and it is console app.
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in));) {
System.out.println("Enter the path");
String path = br.readLine();
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}
Output
Enter the path
./file/test.txt
File is created!
with interface, for simplest way to get user input
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JOptionPane;
public class CreateFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String path = JOptionPane.showInputDialog("Enter the path");
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
System.out.println("File is created!");
}
}
}
here is Java Swing – JOptionPane showInputDialog example
Related
I would like to import a file path in Java. Since the path can change, I want it to be outside of the code and so it is changeable. I have read that that can solve with an INI file. Well, I've tried it. I have the following Java code:
import java.util.*;
import java.io.*;
class readIni {
public static void main(String args[]) {
readIni ini = new readIni();
ini.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.ini"));
p.list(System.out);
}
catch (Exception e) {
System.out.println(e);
}
}
}
My Ini-file:
file = H:/
Now, the console shows exactly the Ini-file and not the contents of the directory....What is wrong?
If you want to just save a file path, consider using the following code:
File file = new File("H:\whatever.txt");
// Write to the file
FileWriter fw = new FileWriter(file);
fw.write("your path goes here");
fw.close();
// Read from the file
BufferedReader br = new BufferedReader(new FileReader(file));
String path = br.readLine();
br.close();
I am pretty new to Java and I came across this problem. I want the java code to make a txt file if it does not exist already, but if it does, I want PrintWriter to append to it using FileWriter. Here is my code:
Edit: I attempted to fix my code but now I am getting the IOException error. What am I doing wrong here?
Edit 2: I think my code is unique since I am trying to make it create a new file if the file does not exist, and make it append to the existing file if it already exists.
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
/**
* Created by FakeOwl96 on 3/28/2017.
*/
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.nextLine();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class AreaOfCircle {
private static double PI = Math.PI;
private double radius;
private static double area;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
AreaOfCircle a = new AreaOfCircle();
System.out.print("Type in the radius of circle: ");
a.radius = keyboard.nextDouble();
getArea(a.radius);
System.out.print("Name of the txt file you want to create:");
String fileName = keyboard.next();
keyboard.nextLine();
try {
File myFile = new File(fileName);
if (!myFile.exists()) {
myFile.createNewFile();
}
FileWriter fw = new FileWriter(myFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("The area of the circle is " + area + ".\n");
bw.close();
}
catch (IOException e) {
System.out.println("IOException Occured");
e.printStackTrace();
}
}
public static void getArea(double n) {
area = n * PI;
}
}
The only change I made is
String fileName = keyboard.next(); from //keyboard.nextLine()
The above code worked for me . Hope this helps.
Add following line after initializing myFile:
myFile.createNewFile(); // if file already exists will do nothing
This is another example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AppendFileDemo2 {
public static void main(String[] args) {
try {
File file = new File("myfile2.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
//This will add a new line to the file content
pw.println("");
/* Below three statements would add three
* mentioned Strings to the file in new lines.
*/
pw.println("This is first line");
pw.println("This is the second line");
pw.println("This is third line");
pw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
This is an example of file append line and create new file if file is not exists.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileDemo {
public static void main(String[] args) {
try {
String content = "This is my content which would be appended "
+ "at the end of the specified file";
//Specify the file name and path here
File file = new File("myfile.txt");
/* This logic is to create the file if the
* file is not already present
*/
if (!file.exists()) {
file.createNewFile();
}
//Here true is to append the content to file
FileWriter fw = new FileWriter(file, true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();
System.out.println("Data successfully appended at the end of file");
} catch (IOException ioe) {
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Yet, another example, this time with try-with-resources and using the Files class to create the BufferedWriter:
public void write(File file, String text) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
bw.write(text);
}
}
The above example is available on GitHub with tests.
You can also use the Files.write method:
public void write(File file, List<String> lines) throws IOException {
Path path = file.toPath();
Charset charSet = StandardCharsets.UTF_8;
OpenOption[] options = new OpenOption[]{
StandardOpenOption.CREATE, // Create a new file if it does not exist
StandardOpenOption.WRITE, // Open for write access
StandardOpenOption.APPEND // Bytes will be written to the end of
// the file rather than the beginning
};
Files.write(path, lines, charSet, options);
}
I have a file that has data inside of it. In my main method I read in the file and closed the file. I call another method that created a new file inside of the same folder of the original file. So now I have two files, the original file and the file that is being made from the method that I call. I need another method that takes the data from the original file and writes it to the new file that is created. How do I do that?
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
public class alice {
public static void main(String[] args) throws FileNotFoundException {
String filename = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
File textFile = new File(filename);
Scanner in = new Scanner(textFile);
in.close();
newFile();
}
public static void newFile() {
final Formatter x;
try {
x = new Formatter("/Users/DAndre/Desktop/Alice/new1.text");
System.out.println("you created a new file");
} catch (Exception e) {
System.out.println("Did not work");
}
}
private static void newData() {
}
}
If your requirement is to copy your original files content to new file. Then this may be a solution.
Solution:
First, read to your original file using BufferedReader and pass your content to another method which creates new file using PrintWriter. and add your content to your new file.
Example:
public class CopyFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = ("C:\\Users\\yubaraj\\Desktop\\wonder1.txt");
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder stringBuilder = new StringBuilder();
String line = br.readLine();
while (line != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
line = br.readLine();
}
/**
* Pass original file content as string to another method which
* creates new file with same content.
*/
newFile(stringBuilder.toString());
} finally {
br.close();
}
}
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\yubaraj\\Desktop\\new1.txt";
PrintWriter writer = new PrintWriter(newFileLocation);
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have created a thread that should allow the user to input a string of characters into the command line and this should save, on a new line, to a file, called user_input.txt.
I managed to make it work while on the main thread, but I need to make it happen within a Thread.
Here is my code for the Thread object:
//Importing
//Input
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
//File writing
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileInputThread implements Runnable
{
public void run() {
System.out.println("FileInputThread running");
//Creating Instances of InputStreamReader and BufferedReader
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader keyboardInput = new BufferedReader(input);
//Finding/Creating File
File file = new File("/Users/jakecarr/Documents/University/Year 2/Semester 1" +
"/ECM2414 Software Development/Workshop 3/user_input.txt");
try {
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//Creating instances of FileWriter and BufferedWriter
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
//Creating Date object
Date date;
//Output
System.out.println("Type what you want to write to file");
System.out.println("Please type 'ESC' to exit");
while (true) {
System.out.println("Inside While loop");
String string = keyboardInput.readLine();
//Checks if user types in ESC to stop program
if (string.equals("ESC")) {
System.out.println("You are finished");
break;
}
//Writing the input to the file
bw.write(string);
bw.newLine();
//Flushes strings on buffered reader to the hard drive
bw.flush();
}
System.out.println("Writing to file complete");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Right now, it seems to do all the println methods, I just doesn't allow you to type anything in at the command line when it comes to the keyboardInput.readLine(); and that is where it seems to get stuck!
I would be grateful for any help!
Thank you.
I create and write a file with a java method, then I want to read this file at runtime with another java method.But it throws java.io.FileNotFoundException error.
How could I fix this error?
Writer output=null;
File file = new File("train.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(trainVal[0] + "\n");
-------------------
and read code
FileInputStream fstreamItem = new FileInputStream("train.tx");
DataInputStream inItem = new DataInputStream(fstreamItem);
BufferedReader brItem = new BufferedReader(new InputStreamReader(inItem));
String phraseItem;
ArrayList<Double> qiF = new ArrayList<Double>();
while ((phrase = br.readLine()) != null) {
//doing somethinh here
}
Use the correct file name. This includes the path to the file. Also make sure that no one deleted the file between those two functions or renamed it.
The following is one of the best and convenient methods to read a file. Go through it instead of using traditional methods.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
final public class Main
{
public static void main(String... args)
{
File file = new File("G:/myFile.txt"); //Mention your absolute file path here.
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner=null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
String lineSeparator = System.getProperty("line.separator");
try
{
while(scanner.hasNextLine())
{
fileContents.append(scanner.nextLine()).append(lineSeparator);
}
}
finally
{
scanner.close();
}
System.out.println(fileContents); //Displays the file contents directly no need to loop through.
}
}
You have made a mistake in giving a proper file extension in your code.
FileInputStream fstreamItem = new FileInputStream("train.tx");
Should have been
FileInputStream fstreamItem = new FileInputStream("train.txt");