Create multiple files - java

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.

Related

Write to File doesn't persist between activities

I'm writing and reading from a file and it works perfectly fine. However when the activity is switched or the app is closed it appears that the file is deleted or some such as null is returned when trying to read from the file. I believed it may be because I have an onCreate blank write to the file but that should only run upon the launch to make sure the file is created. I don't mind if the file doesn't persist between launches however it should at least persist between activities.
//in oncreate is writeToHistory("");
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void btnAnsClicked(View v) throws IOException {
File path = getApplicationContext().getFilesDir();
File file = new File(path,"JWCalcHistory.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String oldAns = br.readLine();
if (!(oldAns.equals("null") || oldAns.equals(""))) {
if (Character.isDigit(readableSum.charAt(readableSum.length() - 1))) {
oldAns = "*" + oldAns;
}
UpdateSum(oldAns);
}
}
If someone can point out a way to make the contents of the file persist always until it is programmatically deleted or cleared then please let me know. The file doesn't already exist and is created upon the code being run.
You need to check if the file exists first. Something like this:
public void writeToHistory(String toWrite) {
try {
File path = getApplicationContext().getFilesDir();
File file = new File(path, "JWCalcHistory.txt");
if(file.exists()) return;
FileOutputStream fos = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(toWrite);
bw.close();
} catch (Exception e){
e.printStackTrace();
}
}

BufferedWriter do not write to a file

I am trying to make a text editor, but I am unable to save the contents to a text file : the file is created but empty.
class Saver implements ActionListener{
public void actionPerformed(ActionEvent e){
try{
File file = new File("projekat");
if(!file.exists()){
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(tekst1);
bw.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
}
JTextArea code
area = new JTextArea(tekst1, 30,30);
tekst1 = area.getText();
Please help me. Best regards
The problem is that you need to call tekst1 = area.getText();
again in your actionPerformed method to update the contents of tekst1.
class Saver implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
File file = new File("projekat");
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// get latest contents of the JTextArea
tekst1 = area.getText();
bw.write(tekst1);
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
bw.write(tekst1);
this line writes the content to the file.
you were close, the string you are writing is just empty, so it's normal that nothing writes to the file.
Some examples:
http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/
http://www.tutorialspoint.com/java/io/bufferedwriter_write_string.htm
http://beginnersbook.com/2014/01/how-to-write-to-file-in-java-using-bufferedwriter/
include only this code :---
file.createNewFile();
in your if statement and place other things out of your if.

How to create a txt file in Java?

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 ^^
}

Java WriteFile can't see contents

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();

Writing to multiple files without duplicating code Java

I have this code to write to a file when I add a user to an array list. The code works fine:
public void writeToFile(String content)
{
try {
File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
I want to write to a separate file when a user does something differently (say, request a permission upgrade). Is there any way I can write to a new file "UserRequests.txt" without duplicating this code?
Why not make the method more general?
public void writeToFile(String content, String fileName, String path)
{
try {
File file = new File(path + fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
}
}
Then you could use the method for writing all kinds of files :3
You should probably just use a 2nd argument, as in the following.
Moreover, you should close your Writers in a finally block. That way, you would be sure that the Writers are closed even if a exception occurred while writing.
public void writeToFile(String content, String path)
{
FileWriter fw
BufferedWriter bw
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(content + "\n" );
bw.close();
logger.info("Recorded to User Activity file");
} catch (IOException e) {
e.printStackTrace();
} finally {
bw.close();
fw.close();
}
}
I would just pass in the file you want to write to:
public void writeToFile(String content, String filename){
And then:
File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);

Categories

Resources