I'm just want a program to register a user and then create a txt file to store there the information. I know it has to be with createNewFile method but I do not know how to use it. I'd try this in my code:
import java.util.*;
public class File{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
byte option=0;
do{
System.out.println("\nMENU:\n");
System.out.println("0.-EXIT");
System.out.println("1.-REGISTER USER");
System.out.println("\nPLEASE ENTER YOUR CHOICE:");
option = sc.nextByte();
}while(option!=0);
}//main
}//File
You can use a File object to create a new File an example is:
File createFile = new File("C:\\Users\\youruser\\desktop\\mynewfile.txt");
createFile.createNewFile();
If you want to read and write to the file you could use a PrintWriter or some other writing mechanism:
PrintWriter pw = new PrintWriter(createFile);
pw.write("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
If you need to append to the file you can do this:
PrintWriter pw = new PrintWriter(new FileOutputStream(createFile, true)); //true means append here
pw.append("File Contents");
//when you are done flush and close the pw
pw.flush();
pw.close();
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("/users/your_user_name/filename.txt");// unix case
File file = new File("c:\\filename.txt"); //windows case
// 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();
}
}
}
Source: http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
Ok so once you have the input from the user this is what you would use to write the username and password to a text file
try {
File file = new File("userInfo.txt");
BufferedWriter output = new BufferedWriter(new FileWriter(file, true));
//set to true so you can add multiple users(it will append (false will create a new one everytime))
output.write(username + "," + password);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
EDIT***
You can put all this in a method and call it every time you want to add the user
public void addUser(String username, String password){
//my code from above ^^
}
Related
I am trying to write to a file, which another process can read. I am using the Printwiter to write to a file. But it doesnt write to the file as long as i dont terminate the program. I have eanbles the autflush on, and even explicitly flusing. The code is below -
import java.io.FileWriter;
import java.io.PrintWriter;
public class ReadFile {
public static void main(String[] args) {
try {
// Create a print writer
FileWriter fw = new FileWriter("D:\\SpringProjects\\RescilienceModel\\natural_resource.txt");
//BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(fw, true);
// Experiment with some methods
while(true)
{
pw.println(99);
pw.flush();
}
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Two issues.
Check that while(true) loop, or it won't end.
close() your handle, or it won't release resources.
I have this code:
try {
File file = new File(something+counter+".txt");
counter++;
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
I need to make it like this: When they press enter, new file will be created in defined location (I made JTextField for this), but when they press it again, the file OVERWRITES. That's the problem. I need them to press enter - create new file: sample1.txt, press enter again, create new file: sample2.txt
OK by looking at your code now, it looks fine, but you probably declared the counter variable within the method. If so, it will be 'reset' to whatever you set it to every time the method is called.
EDIT:
This should work.
import java.io.*;
public class Example {
public static void main(String args[]) {
Example ex = new Example();
ex.writeFile();
ex.writeFile();
}
private void writeFile() {
try {
File file = new File("file" + counter + ".txt");
counter++;
System.out.println("Writing to " + file.toString());
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("content");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private int counter = 0;
}
I get
Writing to file0.txt
Writing to file1.txt
as output and both files have the string 'content' written in them.
EDIT2:
Call writefile whenever the user presses enter.
I have a program that is suppose to read all the files in my folder and combine the files into on file and place them into a new folder. Some of the files are not being pulled in and I do not know why.
The file names are wonder1.txt, wonder2.txt, wonder3.txt, and wonder4.txt and the folder name is Alice, but only a few of the files are actually in the new folder.
import java.io.*;
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.PrintWriter;
public class alice {
public static void main(String[] args) throws FileNotFoundException, IOException {
File folder = new File("/Users/DAndre/Desktop/Alice");
//Reads in all the files in that folder
for (final File fileEntry : folder.listFiles()) {
String fileName = fileEntry.getAbsolutePath();
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 = "/Users/DAndre/Desktop/final/final_copy.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();
}
}
}
The problem with your solution is that you haven't initialize PrintWriter in append mode, because of which the new file gets overwritten with the content of the last file that was written.
public static void newFile(String fileContent) {
try {
String newFileLocation = "C:\\Users\\Shayan\\Desktop\\files2\\final_copy.txt";
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(newFileLocation), true /* append = true */));
writer.write(fileContent);//Writes original file content into new file
writer.close();
System.out.println("File Created");
} catch (Exception e) {
e.printStackTrace();
}
}
The last argument in the constructor of FileOututStream is set to true, indicating that it should be opened in append mode.
You need to change
PrintWriter writer = new PrintWriter(newFileLocation);
to
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(newFileLocation, true)))
Little explanation: append meant to write it additively, on the contrary write overrides the existing file. In your code you are creating a new file including one of your wonders, but on next iteration the file is recreated. So the content of previous wonder is gone.
With the change PrintWriter object is not recreating the file, instead it writes content to a BufferedWriter which also transfers the stream to an append able FileWriter object.
Little suggest: do not create a PrintWriter object on each iteration.
Second little suggest: You don't need PrintWriter. BufferedWriter itself is good enough as far as I see.
I want to create a simple text file with some text in it.
import java.io.*;
class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public static void main(String args[]){
writeTextFile("myText.txt","some text");
}
}
When i run this code i successfully create the text file but when i open it i don't see the contents ("some text"). What am I doing wrong?
You're closing underlying FileWriter but actual data are still stored (buffered) in BufferedWriter object. That's the object you have to close:
FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();
I just started doing file I/O andim using an example from Murach's Se 6.
Here is my code. Am i missing something. I know the code further on has more but as this is an example this should work right?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//Answer
by adding a throws exception to the end of where i initialised the main this code works. Even the txt file products.txt is in the class folder as expected.
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
The problem is that a number of the calls to the java.io package throw exceptions.
easy fix: add the following to your method signature
public static void main(String[] args) throws IOException
almost as easy fix: add try/catch/finally blocks.
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = null;
try {
out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
}
catch(IOException ex) {
// todo exception handling
System.out.println("ERROR! " + ex);
}
finally {
out.close();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
}
catch (IOException ex) {
// todo more exception handling
System.out.println("ERROR! " + ex);
}
finally {
in.close();
}
}
edit: you know you are trying to call out.close() twice? The second should be a call to in.close()