Java Text editor - How to create New File - java

I followed this tutorial on how to create a simple text editor in Java, but the person who wrote the tutorial seems to have left out how to create a new file http://forum.codecall.net/topic/49721-simple-text-editor/
For the most part I was able to follow the guide, but I have no idea how one would create the 'New File' functionality.

you can write code like this to create new file :
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}

When you click on the save button on your text editor, include this in your actionPerformed() method -
FileDialog fd=new FileDialog(f1,"Save Your File",FileDialog.SAVE);
fd.setSize(400,200);
fd.setVisible(true);
try
{
FileWriter fw=new FileWriter(fd.getDirectory()+fd.getFile());
fw.write(t1.getText()); // t1 is the name of your textarea
fw.close();
}
catch(Exception e)
{
}

Related

Android studio, open a file , continuously write and then close

I have code that is generating data every second and displaying onscreen.
This all works fine but I want to create a log file of all the data to analyze later.
I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file
String data= reading1","+reading2+","+time +"/n";
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
I would prefer to have the file open when the start button is clicked.
if ( v.getId() == R.id.start ){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
but when it comes to closing the file, no options for .close() appear when out is typed
if ( v.getId() == R.id.stop ){
// checks which button is clicked
out. // no valid options appear
messageValue.setText(R.string.stopButtonText);// changes the hallo world text
readNoRead=false;
}
Does all the open/write/close need to be together or is it possible to
***open file***
-----
Cycle through all the data
-----
***Close file***
You should store a link to your FileOutputStream on top level in your class.
Example to your code:
FileOutputStream out;
void clickStart() {
if (v.getId() == R.id.start){
// checks which button is clicked
Log.d("dennis", "Scan working"); //logs the text
// open a file
try {
out = openFileOutput("data.csv", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void writeData() {
String data= reading1+","+reading2+","+time +"/n";
try {
out.write(data.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
void clickStop() {
if (v.getId() == R.id.stop) {
try {
out.close();
} catch(IOException e) {
e.printStackTrace();
}
messageValue.setText(R.string.stopButtonText);// changes the hello world text
readNoRead=false;
}
}
It is definitely possible to open, process and close a file all in one block without closing the file.
Your out variable is not showing any method suggestions because it has not been defined in that block. Change the line
FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
to
out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);
and then add FileOutputStream out; to a line above the first if statement (outside of the block).
You may want to also look into 'try-catch-finally', or 'try with resources' as options for closing files in a try-catch block.

How do I edit the information in a RandomAccessFile?

I have managed to save two separate pieces of information in the file below. But I would love to know how I can go about editing the info in this file.
try {
RandomAccessFile fileWriter = new RandomAccessFile("Officers.txt", "rw");
fileWriter.seek(fileWriter.length());
fileWriter.writeUTF(officerObject.getOfficerBadgeNum());
fileWriter.writeUTF(officerObject.getOfficerFirstName());
fileWriter.writeUTF(officerObject.getOfficerLastName());
fileWriter.writeUTF(officerObject.getOfficerPrecint());
fileWriter.close();
System.out.println("Data Successfully Saved");
}
catch (IOException e) {
System.out.println("Error in File. Could not SAVE Officer");
e.printStackTrace();
}

Trying to send data to text file

Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..

How to Create or edit a txt file in a folder in Java?

I'm trying to make save files for a game i'm making, these files will have multiple txt files in them. My problem is that both the folder and the txt file wont create themselves in the directory I specify, here is the code for the folder:
File folde = new File("c:/Users/Mike/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
Here is the code for the file:
try{
PrintWriter writer = new PrintWriter("c:/Users/Mike/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
And here is the entire Class:
package files.maintain;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import vars.all.*;
public class SaveFile {
MainStart Start = new MainStart();
Stats Stats = new Stats();
public void save(){
Scanner in = new Scanner(System.in);
System.out.println("What should I save as?");
String save = in.nextLine();
File folde = new File("c:/Users/Dave/Desktop/Saves/bob/" + save);
try{
if (!folde.exists()) {
if (folde.mkdirs()) {
System.out.println("Created new save file");
} else {
System.out.println("Did not create new save file");
}
}
}finally{
System.out.println("Folder found.");
}
try{
PrintWriter writer = new PrintWriter("c:/Users/Dave/Desktop/javafiles/Saves/" + save + "/Stats.txt", "UTF-8");
writer.println(Stats.Health);
writer.println(Stats.Strength);
writer.println(Stats.Constitution);
writer.println(Stats.Dexterity);
writer.println(Stats.Inteligence);
writer.println(Stats.Wisdom);
writer.println(Stats.Charisma);
writer.close();
} catch (IOException x) {
System.err.println("Could not create save file.");
}
}
}
The Response i'm getting from the console is:
What should I save as?
bob
Folder found.
Could not create save file.*
My input is in bold,
I checked this website: http://www.mkyong.com/java/how-to-create-directory-in-java/
And the java tutorials: http://docs.oracle.com/javase/tutorial/essential/io/file.html
But that didn't work.
Thanks!
Make paths consistent if not the same. Instead of using string constants, use a single Java File object. You are using these 2 inconsistent prefixes:
"c:/Users/Dave/Desktop/Saves/bob/"
"c:/Users/Dave/Desktop/javafiles/Saves/"
Also, you need to improve your exception handling and reporting. Log as much information as you can about the original exception and the corrective (or emergency) action your program is taking.

Why do I get FileNotFoundException when I create and try to write to file on Android emulator?

First off, I am not trying to write to the SDCard. I want to write some information to a file that persists between uses of the app. It is essentially a file to hold favorites of the particular user. Here is what the code looks like:
try {
File file = new File("favorites.txt");
if (file.exists()) {
Log.d(TAG, "File does exist.");
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
}
else {
Log.d(TAG, "File does not exist.");
return favDests;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
When running this code, we always get the "File does not exist." message in our DDMS log.
We have also tried the following code to no avail:
try {
File file = new File(GoLincoln.FAV_DEST_FILE);
fis = new FileInputStream(file);
br = new BufferedReader(new InputStreamReader(fis));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is this second portion of code that results in the FileNotFoundException.
I have read multiple tutorials on writing and reading files on Android and I believe I am following them pretty closely, so I am not sure why this code doesn't work successfully. I appreciate any help!
You shouldn't use the File class directly. Use Activity.getCacheDir() to get the cache dir which is specific to your application. Then use new File(cachedir, "filename.tmp") to create the file.
Preferences and SQLLite will both allow you to have persistent data without managing your own files.
To use shared preferences you grab it from your context, then you edit the values like so
mySharedPreferences = context.getSharedPreferences("DatabaseNameWhateverYouWant", 0);
mySharedPreferences.getEditor().putString("MyPreferenceName", "Value").commit();
To get a preference out
mySharedPreferences.getString("MyPreferenceName", "DefaultValue");
This is really the simplest way to do basic preferences, much easier then doing a file. More then strings are supported, most basic data types are available to be added to the Preferences class.

Categories