Iterator writing to File.txt Java - java

Here is my issue: I need to write the Interator to the file "random.txt" I am able to see all the data. The data is Store where suppose to, I can see it with the System.out.print but my file is in blank. I am able to create the file but not to writer to it.
I am reading a file from my comp. store in the Treemap and trying to write to the text file. ( I am able to doit with Array with not problem) But this Map with Iterator is bouncing my head.
If some one can help me a litter I will appreciated.
I need to use the TreeMap and the Iterator.
public static void main(String[] args) throws FileNotFoundException, IOException {
Map<String, String> Store = new TreeMap<>();
Scanner text=new Scanner(System.in);
System.out.println("enter file: ");
//C:\Users\Alex\Desktop\Fruits\fruits.txt
String rap=text.next();
File into = new File(rap);
try (Scanner in = new Scanner(into)) {
while (in.hasNext()){
String name=in.next();
String fruta = in.next();
Integer num= Integer.parseInt(in.next());
System.out.println(fruta+"\t"+name+"\t"+num);
if (Store.containsKey(fruta)){
Store.put(name,Store.get(name)+fruta );
}
else{
Store.put(name,fruta);
}
}
in.close();
}
System.out.println();
// insert data to store MAP
Set top=Store.entrySet();
Iterator it = top.iterator();
// debugging
System.out.println(top);
// Creating file???????
FileWriter fstream = new FileWriter("random.txt");
//identify File to be write??????
BufferedWriter out = new BufferedWriter(fstream);
//iterator Loop
while(it.hasNext()) {
Map.Entry m = (Map.Entry)it.next();
String key = (String)m.getKey();
String value = (String)m.getValue();
//writing to file?????
out.write("\t "+key+"\t "+value);
// debugging
System.out.println(key +"\t"+ value);
}
System.out.println("File created successfully.");
}

After your while loop (the one writing to file) is finished, do:
out.flush();
out.close();
Short explanation: BufferedWriter buffers in memory what you write. It doesn't immediately write to file when you call the write method. Once the while loop is finished and the data to write to file is prepared in buffer memory, you should call flush to do the actual writing to hard disk. And finally you should always close the BufferedWriter that will no longer be used, to avoid memory leaks.

Related

File isn't written to after program runs

So i'm trying to write to a file to use as a save point to access later, but i cant actually get it to write to the file. I'm trying to save the components of a class to access next time I open and run the program, by writing a string with the PIV's to the file as a save method and by using a scanner to search for tags at the beginning of each line to access later. My code so far though, will not actually write to the file. It compiles and runs fine, but the file shows being unchanged after the program runs.
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
String save = new String();
while(sc.hasNextLine())
{
save=sc.nextLine();
}
byte buf[]=save.getBytes();
FileOutputStream fos = new FileOutputStream(f);
for(int i=0;i<buf.length;i++)
fos.write(buf[i]);
if(fos != null)
{
fos.flush();
fos.close();
}
}
If anyone has a way to fix the code or even a better idea for saving please let me know, thanks
You are replacing save value in every single nextLine.
Change this line:
save = sc.nextLine();
to this one:
save += sc.nextLine();
Also, it's better to use a FileWriter when you are writing String to a file.
And because String is immutable, it will be a slow procedure. Consider using StringBuilder or CharBuffer instead of simple solution which I mentioned above.
Look at code included below:
public static void main (String[] args) throws Exception
{
File f = new File("SaveFile");
Scanner sc = new Scanner(f);
StringBuilder builder = new StringBuilder();
while (sc.hasNextLine())
{
builder.append(sc.nextLine() + "\n");
}
String save = builder.toString();
FileWriter writer = new FileWriter(f);
writer.write(save);
writer.close();
}
Also close() implicitly calls flush().

Program terminates while trying to sort doubles

I'm trying to create a method where it reads doubles from my .txt file which looks like:
Homer Simpson, 50.0
Zoidberg, 100
Peter Griffin, 34.0
Lisa Simpson, 100
and sort them in descending order, here's my code:
public static void sortGrade() throws IOException {
FileReader reader = new FileReader("Grades.txt");
BufferedReader buffer = new BufferedReader(reader);
Scanner input = new Scanner ("Grades.txt");
Double dGrade=0.0;
ArrayList<Double> grade = new ArrayList<Double>();
while (input.hasNextDouble())
{
grade.add(dGrade);
}
reader.close();
Collections.sort(grade, Collections.reverseOrder());
FileWriter fileWriter = new FileWriter("Grades.txt");
PrintWriter out = new PrintWriter(fileWriter);
for (Double outputLine : grade)
{
out.println(outputLine);
}
out.close();
}
}
After I call the method, it deletes my .txt file and terminates the program. Does anyone know what i'm doing wrong syntactically or logically?
You have several problems in your code:
You declare BufferedReader buffer = new BufferedReader(reader); but never use the buffer to read the data, instead you use the Scanner input.
Scanner input = new Scanner ("Grades.txt"); uses Scanner(String) which means it will use the String parameter as the source to read the data. You should pass it as a File instead, like this:
Scanner input = new Scanner(new File("Grades.txt"));
You're creating an output file with the same name and path of the input file, noted here:
FileWriter fileWriter = new FileWriter("Grades.txt");
Use a different name and location for this file, like:
FileWriter fileWriter = new FileWriter("Grades-out.txt");
In case you want/need to append data to the end of the output, then use FileWriter(String, boolean) and pass the second parameter as true.
FileWriter fileWriter = new FileWriter("Grades-out.txt");
Be aware that when you use this approach you have to manually clear the file before executing the application, otherwise you may have duplicated data in your input.
From 2, since you haven't read any double from "Gradex.txt" string, then there's no output in the file, so the current output file, Grades.txt, will be an empty file.
I recommend you to create a class called Person where you store both the name string and the double (whatever it means), then store every instance of Person in a List<Person> (backed by an ArrayList<Person>) and sort this list using a custom Comparator<Person> or by implementing Comparable<Person> in Person class.
You can use something like this (I always use a charset for reading, if you don't need it just don't use it):
List<Double> result = new LinkedList<>();
try (Scanner scanner = new Scanner(Paths.get("Grades.txt"), StandardCharsets.UTF_8.name())) {
while (scanner.hasNextLine()) {
result.add(Double.valueOf(scanner.nextLine().split(",")[1]));
}
} catch (IOException e) {
System.err.printf("Something happened here...this is why: %s", e);
}
Collections.sort(result, Collections.reverseOrder());
// Do your other stuff from now on...

Java deletes my file and creates a new one

I am trying to finish a bank accounts homework assignment. I have a text file, "BankAccounts.txt" which is created if there is no file with that name. However, if the file exists, I do not create it. But Java desides to delete all my code inside of it :(. Can you help me identify why this happens? Thanks <3
Code:
static Scanner keyboard = new Scanner(System.in);
static File file;
static PrintWriter Vonnegut; //a great writer
static FileReader Max;
static BufferedReader Maxwell;
public static void main(String[] args) {
initialize();
}
static void initialize(){
try { // creating banking file
file = new File("src/BankAccounts.txt");
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
Max = new FileReader("src/BankAccounts.txt");
Maxwell = new BufferedReader(Max);
//get list of usernames and passwords for later
usernames = new String[countLines() / 5];
passwords = new String[usernames.length];
checkingAccounts = new String[usernames.length];
savingsAccounts = new String[usernames.length];
} catch (IOException e) {
e.printStackTrace();
}
}
And this method keeps returning 0... regardless of whether or not my file has data in it.
static int countLines() throws IOException {
BufferedReader Kerouac = new BufferedReader(Max);
int lines = 0;
while(Kerouac.readLine() != null)
lines++;
Kerouac.close();
System.out.println(lines);
return lines;
}
After I run the program, unless I call a method that writes to the file, all the contents of the file will be gone.
if(!file.isFile()) {file.createNewFile();} //if it doesn't exist, create it
Redundant. Remove.
Vonnegut = new PrintWriter("src/BankAccounts.txt","UTF-8");
This always creates a new file, which is why the previous line is redundant. If you want to append to the file when it already exists:
Vonnegut = new PrintWriter(new FileOutputStream("src/BankAccounts.txt", true),"UTF-8");
The true parameter tells the FileOutputStream to append to the file.
See the Javadoc.
Or use a FileWriter instead of a FileOutputStream, same principle.
When you create a PrintWriter it will always delete the file if it already exists, from the javadoc:
... If the file exists then it will be truncated to zero size ...
(i. e. its content will be deleted)
Instead of using FileReader and PrintWriter you need to use a RandomAccessFile to write and/or read your file in this way:
RandomAccessFile myFile = new RandomAccessFile("/path/to/my/file", "rw");
In this way the file is automatically created if it doesn't exist, and if it does, it just opens it.

How to overcome out of memory exception with PrintWriter?

The following code reads a bunch of .csv files and then combines them into one .csv file. I tried to system.out.println ... all datapoints are correct, however when i try to use the PrintWriter I get:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space.
I tried to use FileWriter but got the same error. How should I correct my code?
public class CombineCsv {
public static void main(String[] args) throws IOException {
PrintWriter output = new PrintWriter("C:\\User\\result.csv");
final File file = new File("C:\\Users\\is");
int i = 0;
for (final File child: file.listFiles()) {
BufferedReader CSVFile = new BufferedReader( new FileReader( "C:\\Users\\is\\"+child.getName()));
String dataRow = CSVFile.readLine();
while (dataRow != null) {
String[] dataArray = dataRow.split(",");
for (String item:dataArray) {
System.out.println(item + "\t");
output.append(item+","+child.getName().replaceAll(".csv", "")+",");
i++;
}
dataRow = CSVFile.readLine(); // Read next line of data.
} // Close the file once all data has been read.
CSVFile.close();
}
output.close();
System.out.println(i);
}
}
I can only think of two scenarios in which that code could result in an OOME:
If the file directory has a very large number of elements, then file.listFiles() could create a very large array of File objects.
If one of the input files includes a line that is very long, then CSVFile.readLine() could use a lot of memory in the process of reading it. (Up to 6 times the number of bytes in the line.)
The simplest approach to solving both of these issues is to increase the Java heap size using the -Xmx JVM option.
I can see no reason why your use of a PrintWriter would be the cause of the problem.
Try
boolean autoFlush = true;
PrintWriter output = new PrintWriter(myFileName, autoFlush);
It creates a PrintWriter instance which flushes content everytime when there is a new line or format.

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
}
}
}

Categories

Resources