For-loop not executing File writing commands - java

I have a program that is supposed to generate a file with a random integer name and append 200 characters of data to each file. I have already succeeded in being able to create a file:
BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(
new File("C:/Users/mirvine/Desktop/SPAM").toPath()));
And I have gotten it to write chars to the file:
bos.write((char)rand.nextInt(255));
But when I combine the two with a for loop, it doesn't work:
try {
while(true) {
int i = rand.nextInt();
File outputFile = new File("C:/Users/mirvine/Desktop/SPAM/"+ String.valueOf(i) +".txt");
bos = new BufferedOutputStream(Files.newOutputStream(outputFile.toPath()));
PrintWriter writer = new PrintWriter(bos);
for(int qu = 0; qu <= 2000; qu++) {
writer.write((char)rand.nextInt(255));
System.out.println("Total " + String.valueOf(qu) + " characters written to " + String.valueOf(i) + ".txt!");
}
System.out.println("File named \'" + String.valueOf(i) + ".txt\' created!");
}
} catch (Exception e) {e.printStackTrace(); return;}
I will get the output "Total: (number) characters written to (whatever).txt!" but it won't actually write the characters. However, if I make the loop infinite (by changing qu++ to qu--) it will write the characters, of course with only one file though. I even tried changing it to a while loop and it didn't work. Any ideas?

Consider changing the use of BufferedOutputStream and PrintWriter for FileWriter, which will take your file as an argument to the constructor.
Also, make sure you flush and close the stream after finishing with it.

You should use a BufferedWriter, it's more efficient, and don't forget to close it at the end. The infinite loop is useless.
int i = rand.nextInt();
File outputFile = new File("C:/Users/mirvine/Desktop/SPAM/"+ String.valueOf(i) +".txt");
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));  
for(int qu = 0; qu <= 2000; qu++)
{
bw.write((char)rand.nextInt(255));
System.out.println("Total " + String.valueOf(qu) + " characters written to " + String.valueOf(i) + ".txt!");
}
bw.close();

Related

How to sort user input to text files in Java?

I have a program taking user input and setting students in a text file, I want to sort these students in separate text files using the grade average
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class NewClass2
{
public static void main(String[] args)
{
String recOut = "";
String delimiter = ",";
Scanner input = new Scanner(System.in);
final int QUIT = 999;
NewClass1 student = new NewClass1();
try
{
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
while(student.getStudentId() != QUIT)
{
System.out.println("Enter Student Last Name: ");
student.setLastName(input.next());
System.out.println("Enter Student First Name: ");
student.setFirstName(input.next());
System.out.println("Enter Student Grade Point: ");
student.setGradePoint(input.nextDouble());
if(student.getGradePoint()>=3.6)
{
Path fileOut = Paths.get("HonorsStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<3.6 && student.getGradePoint()>=2.0)
{
Path fileOut = Paths.get("GoodStandingStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<2.0)
{
Path fileOut = Paths.get("ProbationStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter
+ student.getLastName() + delimiter
+ student.getFirstName() + delimiter
+ student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
}
}
catch(Exception e)
{
System.out.println("<<Something bad happened!>>");
System.out.println(e.getMessage());
}
}
}
I've been experimenting with if statements but that's not working because I can't close the writer correctly causing it to only take in one line then stopping.
How do I do this correctly?
The problem is not with how you're closing the file but with how your opening the file. Every time you're opening the file you are creating a new file and writing one line, then closing it, which is overwriting the old file that existed before. What you want to do is create the file if it does not exist, but if it does exist append one line.
Simply change
Files.newOutputStream(fileOut, CREATE)
to
Files.newOutputStream(fileOut, CREATE, APPEND)
Alternatively, you could open/close the files outside the loop or use “try with resources” too.
Since these are only three files, it is probably the easiest to open all three writers at once at the start and keep them open until the end.
If you don't want to close the writers manually (ans at least java 7 or 8 i think), you can use a try-with-resources statement.
Btw you probably don't need to wrap the OutputStream in a BufferedOutputStream, since you already use a buffered writer.
Instead of writing each time in file why don't you try to make three lists(one for every grade range you need) and when you have no more students then write them to separate files.
Something like this:
List<Student> honorsStudent = new ArrayList<Student>();
List<Student> goodStandingStudent = new ArrayList<Student>();
List<Student> probationStudent = new ArrayList<Student>();
// ....
if (student.getGrade() >= 3.6) {
honorsStudent.add(student);
} else if (student.getGrade() >= 2) {
goodStandingStudent.add(student);
}
else {
probationStudent.add(student);
}
//while loop end
//write your files

How to add a new line after writing a array of characters into a file using JAVA

After executing the following piece of code
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fileOutputStream.write(content.getBytes());
}
catch (IOException e) {
e.printStackTrace();
}
output is as follows:.
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to DrawerCONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)CONSOLIDATED_UNPAID_code_66 _KE = Wrong/Missing Reference
but i want it like
CONSOLIDATED_UNPAID_code_64 _KE = Account Dormant-Refer to Drawer
CONSOLIDATED_UNPAID_code_65 _KE = Wrong/Missing Account Number (EFT)
Pls suggest
I'd have to see the rest of the code to tell you exactly what you should do, but you can simply use the character "\n" in your string.
You can achieve adding new line to a file in quite a few ways, here is the two approaches:
Add a \n to your String which would cause the remainder of the string to be printed in new line
Use PrintWriter's println method to print each string in new line
Also keep in mind that opening a file with Notepad might not recognize \n hence do not display the remainder of string in new line, try opening the file using Notepadd++
String code2 = "code12";
String countryCode2 = "countryCode2";
String reason2 = " \n I am reason.";
String content = new String("CONSOLIDATED_UNPAID_code_" + code2 + "_" + countryCode2 + " = " + reason2);
try {
fout.write(content.getBytes());
//don't forget to flush the output stream
fout.flush();
} catch (IOException e) {
e.printStackTrace();
}
Use PrintWriter as shown below:
String line1 = "This is line 1.";
String line2 = "This is line 2.";
File f = new File("C:\\test_stackoverflow\\test2.txt");
PrintWriter out = new PrintWriter(f);
out.println(line1);
out.println(line2);
//close the output stream
out.close();
First, use a Writer on top of the output stream to write strings to files. This way, you'll be in control of the output character encoding.
Second, if you want to use your platform's line separator, you may use PrintWriter which has println() methods using the correct newline character or character sequence.
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(fileOutputStream, OUTPUT_ENCODING)
);
...
writer.println(content);
Found solution for this . Appending /n wouldnt solve any issue rather use BufferedWriter. BufferedWriter has a inbuilt newline mwthod to do the same. Thanks
Solution:
try {
File file = new File("Danny.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fileOutputStream) );
String content = new String("CONSOLIDATED_UNPAID_description_"+code2+"_"+countryCode2+" = "+description2);
bw.write(content);
bw.newLine();
bw.flush();
check = true;
}
catch (IOException e) {
e.printStackTrace();
}

How can I stop my bufferedWriter from re-writing the text which is already in the file?

I have a BufferedWriter which is being used to write to a file the users details. I have noticed, however, it is not writing to file in the format I want it to, I can't seem to find a method which allows me to write text on a new line without it writing over what is already there or copy out the text already in the file. Is there any way I can edit the following code, to allow it to the above?
Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
try{
//Create writer to write to files.
File file = new File(DirToWriteFile);
FileOutputStream fos = new FileOutputStream(file, true);
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("VirtualATM.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String currentData = "";
while((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
There is no problem with the program (all variables work properly and have been declared somewhere) I have only posted a snippet of the code which is relevant to the question. The current output to the file after running it a few times looks like this
I've got it! Change:
while((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
to:
bw.append(Details);
((BufferedWriter) bw).newLine();
This ensures that no data will be written twice and it will not copy out any text besides the information gained from the user.

Why does this code cause Java to write over the data in a file?

I am not sure as to why the following code causes Java to override the data already in my file every time, when what I want it to do is actually write each new piece of data on a new line. I have included the relevant pieces of code (I understand you might be thinking that there are errors in the variables, but there isn't, the program works fine). Can someone help me understand as to what is causing this, is is the way I am using the file writer?
String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.
String Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
try{
//Create writer to write to files.
File file = new File(DirToWriteFile);
Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("VirtualATM.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String CurrentData = "";
while((bufferedReader.readLine()) != null) {
line = CurrentData;
bw.write(CurrentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
System.out.println(name + " Your card number is: " + CardNo);
// close the reader.
bufferedReader.close();
//Close the writer.
bw.close();
Use the other FileOutputStream constructor, the one that takes a boolean append parameter as the second parameter. Pass in true as this will tell Java to append text to the existing File rather than over-write it.
i.e., change this:
File file = new File(DirToWriteFile);
Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
to this:
File file = new File(DirToWriteFile);
FileOutputStream fos = new FileOutputStream(file, true); // **note second param?**
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));

Write string to huge file

I know there are several threads about this problem but i think my problem is a little bit different because of the size.
In my example I want to write 1,7 million lines to an text file. In worst case there could be much more. This lines are create for the sql loader to load fast data into a table so the file could be very large because sql loader could handle that.
Now I want to write the big file as fast as I could. This is my actually method:
BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt"),40000);
int u=profils.size()-1;
for(int z=0; z<u;z++){
for(int b=0;b<z;b++){
p = getValue();
if(!Double.isNaN(p) & p > 0.55){
bw.write(map.get(z) + ";" + map.get(b) + ";" + p + "\n");
}
}
}
bw.close();
For my 1,7 million lines I need about 20 minutes. Can I handle that faster with any method that I don't know?
FileChannel:
File out = new File("out.txt");
FileOutputStream fileOutputStream = new FileOutputStream(out, true);
FileChannel fileChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = null;
int u=profils.size()-1;
for(int z=0; z<u;z++){
for(int b=0;b<z;b++){
p = getValue();
if(!Double.isNaN(p) & p > 0.55){
String str = indexToSubstID.get(z) + ";" + indexToSubstID.get(b) + ";" + p + "\n";
byteBuffer = ByteBuffer.wrap(str.getBytes(Charset.forName("ISO-8859-1")));
fileChannel.write(byteBuffer);
}
}
}
fileOutputStream.close();
FileChannel is your way to go. It is used for huge amount of writes.
Read the api documentation
here

Categories