TextArea - Any way to get all text? - java

so I'm designing a text editor. For the Open/Save methods, I'm trying to use a TextArea (it doesn't have to be one, it's just my current method). Now, I have two problems right now:
1) When I load a file, it currently doesn't remove the contents currently in the text editor. For example, if I typed in "Owl", then loaded a file that contained "Rat", it would end up as "OwlRat". To solve this, I plan to use the replaceRange method (again however, it isn't absolute, any suggestions would be great!). However, I must replace all the contents of the text editor, not just selected text, and I can't figure out how to do that. Any tips?
2) Currently, when I load a file, nothing will happen unless I saved that file the same time I ran the application. So, for example, running the program, saving a file, closing the program, running the program again, and then loading the file will give nothing. I know this is because the String x doesn't carry over, but I can't think of anyway to fix it. Somebody suggested Vectors, but I don't see how they would help...
Here is the code for the Open/Save methods:
Open:
public void Open(String name){
File textFile = new File(name + ".txt.");
BufferedReader reader = null;
try
{
textArea.append(x);
reader = new BufferedReader( new FileReader( textFile));
reader.read();
}
catch ( IOException e)
{
}
finally
{
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
}
}
}
Save:
public void Save(String name){
File textFile = new File(name + ".txt");
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(textFile));
writer.write(name);
x = textArea.getText();
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
}

I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}

There's a lot going on here...
What is 'x' (hint: it's not anything from the file!), and why are you appending it to the text area?
BufferedReader.read() returns one character, which is probably not what you're expecting. Try looping across readline().
Follow Dave Newton's advice to handle your exceptions and provide better names for your variables.
The text file will persist across multiple invocation of your program, so the lack of data has nothing to do with that.
Good luck.

Use textArea.setText(TEXT); rather than append; append means to add on to, so when you append text to a TextArea, you add that text to it. setText on the other hand will set the text, replacing the old text with the new one (which is what you want).
As far as why it's failing to read, you are not reading correctly. First of all, .read() just reads a single character (not what you want). Second, you don't appear to do anything with the returned results. Go somewhere (like here) to find out how to read the file properly, then take the returned string and do textArea.setText(readString);.
And like the others said, use e.printStackTrace(); in all of your catch blocks to make the error actually show up in your console.

Related

How to Write text file Java

The following code does not produce a file (I can't see the file anywhere).
What is missing?
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
Calendar.getInstance().getTime());
File logFile=new File(timeLog);
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
writer.write (string);
//Close writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases.
The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
In java 7 can now do
try(BufferedWriter w = ....)
{
w.write(...);
}
catch(IOException)
{
}
and w.close will be done automatically
It's not creating a file because you never actually created the file. You made an object for it. Creating an instance doesn't create the file.
File newFile = new File("directory", "fileName.txt");
You can do this to make a file:
newFile.createNewFile();
You can do this to make a folder:
newFile.mkdir();
Using java 8 LocalDateTime and java 7 try-with statement:
public class WriteFile {
public static void main(String[] args) {
String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
File logFile = new File(timeLog);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile)))
{
System.out.println("File was written to: " + logFile.getCanonicalPath());
bw.write("Hello world!");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
You can try a Java Library. FileUtils, It has many functions that write to Files.
It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).
The easiest way for me is just like:
try {
FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
writer.write("Wow, this is so easy!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Useful tips & tricks:
Give it a certain path:
new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
New line
writer.write("\r\n");
Append lines into existing txt
new FileWriter("log.txt");
Hope it works!

How do I quadruple the integer values in a text file? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I guess this comes down to reading and writing to the same file. I would like to be able to return the same text file as is input, but with all integer values quadrupled. Should I even be attempting this with Java, or is it better to write to a new file and overwrite the original .txt file?
In essence, I'm trying to transform This:
12
fish
55 10 yellow 3
into this:
48
fish
220 40 yellow 12
Here's what I've got so far. Currently, it doesn't modify the .txt file.
import java.io.*;
import java.util.Scanner;
public class CharacterStretcher
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner( System.in );
System.out.println("Copy and paste the path of the file to fix");
// get which file you want to read and write
File file = new File(keyboard.next());
File file2 = new File("temp.txt");
BufferedReader reader;
BufferedWriter writer;
try {
// new a writer and point the writer to the file
FileInputStream fstream = new FileInputStream(file);
// Use DataInputStream to read binary NOT text.
reader = new BufferedReader(new InputStreamReader(fstream));
writer = new BufferedWriter(new FileWriter(file2, true));
String line = "";
String temp = "";
int var = 0;
int start = 0;
System.out.println("000");
while ((line = reader.readLine()) != null)
{
System.out.println("a");
if(line.contains("="))
{
System.out.println("b");
var = 0;
temp = line.substring(line.indexOf('='));
for(int x = 0; x < temp.length(); x++)
{
System.out.println(temp.charAt(x));
if(temp.charAt(x)>47 && temp.charAt(x)<58) //if 0<=char<=9
{
if(start==0)
start = x;
var*=10;
var+=temp.indexOf(x)-48; //converts back into single digit
}
else
{
if(start!=0)
{
temp = temp.substring(0, start) + var*4 + temp.substring(x);
//writer.write(line.substring(0, line.indexOf('=')) + temp);
//TODO: Currently writes a bunch of garbage to the end of the file, how to write in the middle?
//move x if var*4 has an extra digit
if((var<10 && var>2)
|| (var<100 && var>24)
|| (var<1000 && var>249)
|| (var<10000 && var>2499))
x++;
}
//start = 0;
}
System.out.println(temp + " " + start);
}
if(start==0)
writer.write(line);
else
writer.write(temp);
}
}
System.out.println("end");
// writer the content to the file
//writer.write("I write something to a file.");
// always remember to close the writer
writer.close();
//writer = null;
file2.renameTo(file); //TODO: Not sure if this works...
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Given that this is a pretty quick and simple hack of a formatted text file, I don't think you need to be too clever about it.
Your logic for deciding whether you are looking at a number is pretty complex and I'd say it's overkill.
I've written up a basic outline of what I'd do in this instance.
It's not very clever or impressive, but should get the job done I think.
I've left out the overwriting and reading the input form the console so you get to do some of the implementation yourself ;-)
import java.io.*;
public class CharacterStretcher {
public static void main(String[] args) {
//Assumes the input is at c:\data.txt
File inputFile = new File("c:\\data.txt");
//Assumes the output is at c:\temp.txt
File outputFile = new File("c:\\temp.txt");
try {
//Construct a file reader and writer
final FileInputStream fstream = new FileInputStream(inputFile);
final BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
final BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile, false));
//Read the file line by line...
String line;
while ((line = reader.readLine()) != null) {
//Create a StringBuilder to build our modified lines that will
//go into the output file
StringBuilder newLine = new StringBuilder();
//Split each line from the input file by spaces
String[] parts = line.split(" ");
//For each part of the input line, check if it's a number
for (String part : parts) {
try {
//If we can parse the part as an integer, we assume
//it's a number because it almost certainly is!
int number = Integer.parseInt(part);
//We add this to out new line, but multiply it by 4
newLine.append(String.valueOf(number * 4));
} catch (NumberFormatException nfEx) {
//If we couldn't parse it as an integer, we just add it
//to the new line - it's going to be a String.
newLine.append(part);
}
//Add a space between each part on the new line
newLine.append(" ");
}
//Write the new line to the output file remembering to chop the
//trailing space off the end, and remembering to add the line
//breaks
writer.append(newLine.toString().substring(0, newLine.toString().length() - 1) + "\r\n");
writer.flush();
}
//Close the file handles.
reader.close();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You may want to consider one of these:
Build the new file in memory, rather than trying to write to the same file you are reading from. You could use StringBuilder for this.
Write to a new file, then overwrite the old file with the new one. This SO Question may help you there.
With both of these, you will be able to see your whole output, separate from the input file.
Additionally, with option (2), you don't have the risk of the operation failing in the middle and giving you a messed up file.
Now, you certainly can modify the file in-place. But it seems like unnecessary complexity for your case, unless you have really huge input files.
At the very least, if you try it this way first, you can narrow down on why the more complicated version is failing.
You cannot read and simultaneously write to the same file, because this would modify the text you currently read. This means, you must first write a modified new file and later rename it to the original one. You probably need to remove the original file before renameing.
For renaming, you can use File.renameTo or see one of the many SO's questions
You seem to parse integers in your code by collecting single digits and adding them up. You should consider using either a Scanner.nextInt or employ Integer.parseInt.
You can read your file line by line, split the words at white space and then parse them and check if it is either an integer or some other word.

how to take the output from command prompt and make a text file out of it using language Java

This is what I have found, but in this code it reads line on what you put in, and I don't want that
I am doing a program called Knight's Tour, and I getting output in Command prompt. All I want to do is to read the lines from Command prompt and store it an output file called knight.txt. Can anyone help me out. Thanks.
try
{
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file (VERY IMPORTANT!)
out.close();
}
catch(IOException e)
{
System.out.println("Error during reading/writing");
}
You don't need Java for that. Just redirect the output of the game to a file:
game > knight.txt
You may look at this example, it shows how write data into an file, if the file exist it show how to append to the file,
public class FileUtil {
public void writeLinesToFile(String filename,
String[] linesToWrite,
boolean appendToFile) {
PrintWriter pw = null;
try {
if (appendToFile) {
//If the file already exists, start writing at the end of it.
pw = new PrintWriter(new FileWriter(filename, true));
}
else {
pw = new PrintWriter(new FileWriter(filename));
//this is equal to:
//pw = new PrintWriter(new FileWriter(filename, false));
}
for (int i = 0; i < linesToWrite.length; i++) {
pw.println(linesToWrite[i]);
}
pw.flush();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the PrintWriter
if (pw != null)
pw.close();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.writeLinesToFile("myfile.txt", new String[] {"Line 1",
"Line 2",
"Line 3"}, true);
}
}
In the code you posted, just change lineFromInput to whatever string you want to output to the text file.
I guess what you are doing is writing the output to file using file operations in java but what you want can be done in an easier way as follows -
No code is required for this. The output can be redirected by
file > outputfile
This is independent of java.

How to write or append string in loop in a file in java?

I'm having memory problem as working with very large dataset and getting memory leaks with char[] and Strings, don't know why! So I am thinking of writing some processed data in a file and not store in memory. So, I want to write texts from an arrayList in a file using a loop. First the program will check if the specific file already exist in the current working directory and if not then create a file with the specific name and start writing texts from the arrayList line by line using a loop; and if the file is already exist then open the file and append the 1st array value after the last line(in a new line) of the file and start writing other array values in a loop line by line.
Can any body suggest me how can I do this in Java? I'm not that good in Java so please provide some sample code if possible.
Thanks!
I'm not sure what parts of the process you are unsure of, so I'll start at the beginning.
The Serializable interface lets you write an object to a file. Any object that implemsents Serializable can be passed to an ObjectOutputStream and written to a file.
ObjectOutputStream accepts a FileOutputStream as argument, which can append to a file.
ObjectOutputstream outputStream = new ObjectOutputStream(new FileOutputStream("filename", true));
outputStream.writeObject(anObject);
There is some exception handling to take care of, but these are the basics. Note that anObject should implement Serializable.
Reading the file is very similar, except it uses the Input version of the classes I mentioned.
Try this
ArrayList<String> StringarrayList = new ArrayList<String>();
FileWriter writer = new FileWriter("output.txt", true);
for(String str: StringarrayList ) {
writer.write(str + "\n");
}
writer.close();
// in main
List<String> SarrayList = new ArrayList<String>();
.....
fill it with content
enter content to SarrayList here.....
write to file
appendToFile (SarrayList);
.....
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter("myContent.txt", myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}

Java save multiline string to text file

I am new to Java and trying to save a multi line string to a text file.
Right now, it does work within my application. Like, if I save the file from my application and then open it from my application, it does put a space between lines. However, if I save the file from my app and then open it in Notepad, it is all on one line.
Is there a way to make it show multi line on all programs? Here's my current code:
public static void saveFile(String contents) {
// Get where the person wants to save the file
JFileChooser fc = new JFileChooser();
int rval = fc.showSaveDialog(fc);
if(rval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
//File out_file = new File(file);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(contents);
out.flush();
out.close();
} catch(IOException e) {
messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
}
}
else {
// Do nothing
System.out.println("The user choose not to save anything");
}
}
depending on how you are constructing your string, you may just be running into a line ending problem. Notepad does not support unix line endings (\n only) it only supports windows line endings (\n\r). try opening your saved file using a more robust editor, and/or make sure you are using the proper line endings for your platform. java's system property (System.getProperty("line.separator")) will get you the proper line ending for the platform that the code is running on.
while you're building your string to be saved to the file, rather than explicitly specifying "\n" or "\n\r" (or on the mac "\r") for your line endings, you would instead append the value of that system property.
like so:
String eol = System.getProperty("line.separator");
... somewhere else in your code ...
String texttosave = "Here is a line of text." + eol;
... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);
Yea as the previous answer mentions the System.getProperty("line.seperator").
your code doesn't show how you created String contents but since you said you were new to java I thought i'd mention that in java concatenating Strings is not nice since it creates a. If you are building the String by doing this:
String contents = ""
contents = contents + "sometext" + "some more text\n"
Then consider using java.lang.StrinBuilder instead
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();
Another alternative is to stream what ever your planning to write to a file rather than building a large string and then outputting that.
You could add something like:
contents = contents.replaceAll("\\n","\\n\\r");
if notepad does not display correctly. However you might run into a different problem: at each save/load you will get multiple \r chars. Then to avoid that at load you would have to call the same code above but with reversed parameters. This is really an ugly solution just to get the text to display properly in notepad.
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}

Categories

Resources