Writing an array to a textfile from a textArea in java - java

I'm new to Java and I am trying to write what I have in a text area called AreaBooking into a textfile. I can get it to write to the textfile but just cant get them on separate lines. I may also have a lot of redundant code but I don't know as I said I'm new to this language.
I want it like
1
2
3
and not 1,2,3
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
AreaBooking.replaceSelection("");
String s[] = AreaBooking.getText().split("\n");
ArrayList<String>arrList = new ArrayList<>(Arrays.asList(s)) ;
System.out.println(arrList);
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(file_name)));
out.write(AreaBooking.getText());
out.close();
} catch (IOException ex) {
Logger.getLogger(ViewBookings.class.getName()).log(Level.SEVERE, null, ex);
}

Instead of
out.write(AreaBooking.getText());
write:
for (String s : arrList) {
out.println(s);
}

Use JTextArea#write(Writer) instead.
try (Writer writer = new BufferedWriter(new WriterReader("Inventory.txt"))) {
textArea.write(writer);
} catch (IOException exp) {
exp.printStackTrace();
}

Related

Any explanation as to why Output Stream only prints the last line of the translated variable to a new file instead of all the lines?

I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one.
public static void newFile(String pigLatin) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt"));
os.write(pigLatin.getBytes(), 0, pigLatin.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter
FileOutputStream(String name, boolean append)
like
os = new FileOutputStream(new File("/Users/...", true))
Take a look at the reference

Java few errors while writing to text file?

I have a java assignment, and my last two errors are laid out in this code. For a little background, my code is taking input from a GUI and writing it into a text file. I realize you may need more code, and I will give more if needed, I just can't seem to understand these errors. Here is my code:
public void dataWriter(String data, String fileName) throws IOException
{
File file = getFileStreamPath(fileName);
if (!file.exists())
{
file.createNewFile();
}
try (FileOutputStream writer = openFileOutput(file.getName(), Context.MODE_PRIVATE)) // Error "cannot find symbol, variable MODE_PRIVATE"
{
for (String string = null, data)//error "variable data is already defined in dataWriter"
{
{
writer.write(string.getBytes());
writer.flush();
}
}
}
catch (Exception e)
{
}
}
Any help is greatly appreciated. Thank you so much!
From the original question it looks as though you are trying to write out to a file. OK, something like this should work:
public void dataWriter(String data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}
The issue you were having with your above code was that the for loop syntax in Java is very different than how you originally stated.
Instead of for (String string = null, data)
An iterative for loop needs to look like this:
for (int i = 0; i < someDataStructure.size(); i++)
someDataStructure.get(i);
You could also do a for each loop if the Data Structure implements Iterable.
However, all this aside, you were attempting to iterate using a FileOutputStream when you had no List or Array over which to iterate, had you passed in another reference to a file or a list, the iteration should have looked something like this:
public void dataWriter(List data, String fileName) throws IOException {
PrintWriter writer = new PrintWriter(new FileOutputStream(new File(fileName));
try {
for (int i = 0; i < data.size(); i++)
writer.write(data);
} catch (Exception e) {
System.err.println("Some exception");
} finally {
writer.close();
}

Java Program keeps inserting the same line into my file

so I am trying to read a file and add two lines of code to it at the top. So far that hadn't been working so I tried just reading the lines and writing them back. This was a major failure. It only writes to one of the files in the directory and just keeps filling it with the xmlopentag even though its been commented out, over and over. If anyone has any ideas it would be appreciated.
ArrayList<String> lines = new ArrayList();
BufferedReader reader = null;
String xmlstylesheet = "<?xml-stylesheet type=\"text/xsl\" href=\""+stylefilename+"\"?>";
String xmlopentag = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
for(int i=0;i<files.length;i++) {
lines.clear();
try {
reader = new BufferedReader(new FileReader(files[i]));
String text = null;
while ((text = reader.readLine()) != null) {
lines.add(text);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
//lines.add(1, xmlstylesheet);
//lines.add(0, xmlopentag);
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(files[i])));
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
} catch (IOException ex) {
Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
writer.write(lines.get(i));
should probably be
writer.write(lines.get(j));
for loop for PrintWriter operation is having an index j for iteration but using i to get the list value
please check it properly and change below code
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(i));
}
to
for(int j=0;j<lines.size();j++) {
writer.write(lines.get(j));
}

java how open file to write

I want to write a file but mixture of 3 bellow feature. how?
BufferedWriter , high volume data write needed
can append to exist text file
can set charset like "cp1256"
How mix all these features to open write file?
What you would do first is, Initiate your BufferedWriter :
`
String fileName = METHOD ARGUMENT, OR REGULAR STRING ("Output.txt");
BufferedWriter writer = null;
try {
File outFile = new File(fileName);
writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer.write(WHAT YOU WANT TO WRITE TO THE FILE);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
Now to explain the code so I'm not just spoon feeding it to you.
When we declare the BufferedWriter writer = null; , we are setting it to null so that we don't write anything without setting a Try/Catch Exception Handler around it.
Once we are within our exception handled, we initiate a File called outFile. This will be the file we are outputting. The Argument we give it is the name of the file name. (A String Value such as, "Output.txt") NOTE: You MUST add the extension or else it won't work the way you are hoping it does.
Next, when we reference our BufferedWriter again, we initiate a new one in the try/catch handler, and inside we initiate a FileWriter (What will be doing the writing to the file). We give it two arguments. The name of the Output File("Output.txt"), and we also supply a true argument. What this does is makes the File Appendable! When we write true, we are saying we want the file to be appendable.
Finally, we write to the file, whatever it is you want to write.
As for the third feature, I don't think that FileWriter's will allow you to choose the Character Encoding that you want to write with, so unless you aren't using UTF-8, then you may want to use a PrintWriter
To do this, you would simply replace our `writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true));
writer = new BufferedWriter(new PrintWriter(outputName, "UTF-8"));
I THINK this should work, if not, please let me know, I'll find a working solution.
public class WriteFile {
BufferedWriter out;
public void openFile(String file){
try {
out = new BufferedWriter(new FileWriter("data.txt"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeInts(int[] ints){
try {
for(int i : ints) out.write(i+" ");
out.newLine();
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeFile(){
try {
if (out!=null)out.close();
} catch (IOException e) {
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
WriteFile wf = new WriteFile();
wf.openFile("test.txt");
wf.writeInts(new int[]{1,2,3,4,5});
wf.writeInts(new int[]{5,4,3,2,1});
wf.closeFile();
BufferedReader bf = new BufferedReader(new FileReader("test.txt"));
System.out.println(bf.readLine());
System.out.println(bf.readLine());
}
}
Output:
Line1: 1 2 3 4 5
Line2: 5 4 3 2 1

Parse String Output to File

The first part of this “Frankenstein-ed” Java works perfectly, however the second part outputs some jumbled nonsense. So the variable of result will be my input from the user. I had to first UpperCase the string before I did the parsing for some dumb reason, it’s hard when you come from the Database/Analysis background and know you do something in seconds and not get an error... I gave credit where credit is due within the code...
myfile.txt ---> [Ljava.lang.String;#19821f
import java.io.*;
/*http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29*/
public class StringParser {
public static void main (String arg[])
throws FileNotFoundException {
String result = "eggs toast bacon bacon butter ice beer".toUpperCase();
String[] resultU = result.split("\\s");
String[] y = resultU;
{
for (int x=0; x< resultU.length; x++)
System.out.println(resultU[x]);
/*http://www.javacoffeebreak.com/java103/java103.html#output*/
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.println (resultU);
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
}
Do you realize you're overwriting the same file for each element in your array?
You should use
out = new FileOutputStream("myfile.txt", true); // appends to existing file
As well as printing the actual element, not the String representation of the whole array
p.println(resultU[x]); // resultU without index prints the whole array - yuk!
Although you should probably update your code to only create the output File once and just write each element of the array to the same output stream, as the current method is a bit inefficient.
Something like
public static void main(String[] args) {
String result = "eggs toast bacon bacon butter ice beer".toUpperCase();
PrintStream p = null;
try {
p = new PrintStream(new FileOutputStream("myfile.txt"));
for (String s : result.split("\\s")) {
p.println(s);
p.flush(); // probably not necessary
}
} catch (Exception e) {
e.printStackTrace(); // should really use a logger instead!
} finally {
try {
p.close(); // wouldn't need this in Java 7!
} catch (Exception e) {
}
}
}
You have to iterate the array and write each element one after one.
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
out = new FileOutputStream("myfile.txt");
p = new PrintStream( out );
for(String str:resultU)
{
p.println (str);
}
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
Your line
p.println (resultU);
is printing a string representation of the array itself, not the elements in it. To print the elements, you'll need to loop through the array and print them out individually. The Arrays class has a convenience method to do this for you, of course.
That "jumbled non-sense" is the Strings location in memory, but that's not important right now.
The solution to your problem is this:
try {
FileOutputStream out = new FileOutputStream("myfile.txt", true);
PrintStream = new PrintStream(out);
for(String s : resultU)
p.println(s);
p.close();
} catch(Exception e) {
e.printStackTrace();
}
This replaces your entire for loop.

Categories

Resources