Java-Write in file - java

I want get name, last name and a spacial code from user, and save in one array, after that write to a file. My code doesn't have compiler error but it doesn't work.
public class WriteFile {
public static void main(String[] args){
try {
String array[][] = new String[100][2];
for (int i = 0; i < array.length; i++) {
RandomAccessFile raf=new RandomAccessFile("D://employee.txt","rw");
String inputName=JOptionPane.showInputDialog("Please Insert First Name");
array[i][0]=inputName;
String inputLName=JOptionPane.showInputDialog("Please Insert Last Name");
array[i][1]=inputLName;
String inputMeliiC=JOptionPane.showInputDialog("Please Insert Melii Code");
array[i][2]=inputMeliiC;
raf.writeUTF(array[i][0]);
raf.writeUTF(array[i][1]) ;
raf.writeUTF(array[i][1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}

You are doing many things wrong.
First of all, why do you use an array at all here? It is unwarranted. Collect in a List!
Second: .writeUTF() will not write text.
Third: why write as you ask for input? Write all at once.
Fourth: you don't close your resource at all.
Ask for input first, then attempt to write to the file. And don't use File, it's obsolete. Use this (supposes Java 7+):
final Path dst = Paths.get("d:\\employee.txt");
// Change open options if necessary
try (
final BufferedWriter writer = Files.newBufferedWriter(dst,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
) {
// write your data
}
Or even better yet, use this. Provided you have collected all of your employee data in a List as I suggest, and not an array, this is as easy as:
Files.write(thePath, myList, StandardCharsets.UTF_8, yourOpenOptionsHere);

Ok well you can for this modified code:
public static void main(String[] args){
RandomAccessFile raf = null;
try {
String array[][] = new String[2][3];
raf=new RandomAccessFile("D:\\employee.txt","rw");
for (int i = 0; i < array.length; i++) {
String inputName=JOptionPane.showInputDialog("Please Insert First Name");
array[i][0]=inputName;
String inputLName=JOptionPane.showInputDialog("Please Insert Last Name");
array[i][1]=inputLName;
String inputMeliiC=JOptionPane.showInputDialog("Please Insert Melii Code");
array[i][2]=inputMeliiC;
raf.writeChars(array[i][0]);
raf.writeChar(':');
raf.writeChars(array[i][1]) ;
raf.writeChar(':');
raf.writeChars(array[i][2]);
raf.writeChars("\n");
}
raf.seek(0);
String str = raf.readLine();
while(str != null ){
System.out.println(str);
String arr[] = str.split(":");
System.out.println(Arrays.asList(arr));
str = raf.readLine();
}
raf.close();
} catch (FileNotFoundException e) {
try {
raf.close();
} catch (IOException ex) {
Logger.getLogger(Ideone.class.getName()).log(Level.SEVERE, null, ex);
}
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
try {
raf.close();
} catch (IOException ex) {
Logger.getLogger(Ideone.class.getName()).log(Level.SEVERE, null, ex);
}
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}

Couple of issues:
You defined array as new String[100][2] and using it till the index array[i][2]=inputMeliiC; As array starts from 0, you should define your array as new String[100][3]. Are you doing further processing on your array?
You are not writing the inputMeliiC, instead you are duplicating the inputLName bu doing raf.writeUTF(array[i][1]); twice. You should do raf.writeUTF(array[i][2]);
Most importantly why you r write is not working is, you need to flush out the buffer. So you should do raf.close(); once you are done. Make sure UTF wont write in simple text as you are entering and you are opening file in both read write mode.

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

EOFexception caused by empty file

I created a new file roomChecker which is empty. Now when I read it, it throws me an EOFException which is undesirable. Instead I want it to see that, if file is empty then it would run other two functions that are in if(roomFeed.size() == 0) condition. I could write this statement in EOFException catch clause; but that's not what I want to do because then every time when the file will be read and reaches end of file it will execute those functions. Instead when the file has some data it should do what is specified in else.
File fileChecker = new File("roomChecker.ser");
if(!fileChecker.exists()) {
try {
fileChecker.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to create new File");
}
}
try(FileInputStream fis = new FileInputStream("roomChecker.ser"); ObjectInputStream ois = new ObjectInputStream(fis)) {
roomFeed = (List<roomChecker>) ois.readObject();
System.out.println("End of read");
if(roomFeed.size() == 0) {
System.out.println("your in null if statement");
defaultRoomList();
uploadAvailableRooms();
} else {
for(int i=0; i<roomNumber.size(); i++) {
for(int j=0; j<roomFeed.size(); i++) {
if((roomNumber.get(i)).equals(roomFeed.get(i).getRoomNumSearch())){
System.out.println("Reach Dead End for now");
} else {
defaultRoomList();
uploadAvailableRooms();
}
}
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
All this:
if(!fileChecker.exists()) {
try {
fileChecker.createNewFile();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Unable to create new File");
}
}
is a complete waste of time, and it is one of two possible causes for your empty file problem. Creating a file just so you can open it and then get a different problem instead of coping correctly with the original problem of the file not being there isn't a rational strategy. Instead, you should do this:
if (fileChecker.isFile() && fileChecker.length() == 0) {
// file is zero length: bail out
}
and, in the following code, this:
try(FileInputStream fis = new FileInputStream(fileChecker); ObjectInputStream ois = new ObjectInputStream(fis)) {
// ...
}
catch (FileNotFoundException exc) {
// no such file ...
}
// other catch blocks as before.
Of course you can still get EOFException if you read the file to its end, or if the file is incomplete, and you still need to handle that.

Writing an array to a textfile from a textArea in 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();
}

Write more than 65535 rows in a csv file

[Update]Problem is different, nothing about csv file format. Question
would be "While using File Writer to write a csv file last few records
are missing.
In my java application i need to append more than 65535 rows in a csv file. but it only writes 65535 rows in a sheet. I haven't used any libraries. some final records missing. how to resolve this..........
public void writeSubmission(){
try {
writer = new FileWriter("res/sample.csv");
writer.append("PhraseId");
writer.append(',');
writer.append("Sentiment");
writer.append('\n');
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void readTestData(){
String path="res/test.tsv";
Calculation cal=new Calculation();
int counter=0;
try {
BufferedReader bReader = new BufferedReader(new FileReader(path));
String line;
writeSubmission();
bReader.readLine();
while ((line = bReader.readLine()) != null) {
String datavalue[] = line.split("\t");
writer.append(datavalue[0]);
writer.append(',');
try {
double value=cal.calculate(datavalue[2]);
System.out.println(value);
String val;
if(value<-0.4)
{
val="0";
}
else if(value>-0.4 && value<-0.1)
{
val="1";
}
else if(value>-0.1 && value<+0.1)
{
val="2";
}
else if(value>+0.1 && value<+0.40)
{
val="3";
}
else{
val="4";
}
counter++;
writer.append(val);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e);
}
writer.append('\n');
}
System.out.println(counter);
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(e);
} catch (IOException e){
e.printStackTrace();
System.out.println(e);
}
}
I think your issue is probably that the tool you're opening up the CSVs with on the other end doesn't want more than 65535 rows, not that Java's doing anything wrong. It's a bug on the other end, not your Java code, almost certainly. (FileWriter wouldn't care at all about 65535 lines, for example.)
If you're using Excel 2003, for example, you'd see this issue: How to get around 64k row limit in Excel
Finally i fixed the error.File Writer should be flush after used in the code push existing stream. OR should be close the writer it automatically flush and close
The flush method flushes the output stream and forces any buffered
output bytes to be written out. The general contract of flush is that
calling it is an indication that, if any bytes previously written have
been buffered by the implementation of the output stream, such bytes
should immediately be written to their intended destination.
writer = new FileWriter("res/sample.csv");
writer.flush();
writer.close();

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