Java Having trouble saving file - java

I am trying to have my program save, but whenever I try to save a program that exists (so the second run through) it creates the temp, but it does not overwrite the old file.
Here is the code. Can anyone find out why it does not overwrite the old file with the new?
public static void saveBallotData(int i)throws IOException{
PrintWriter outputFile;
outputFile = new PrintWriter("temp2.txt");
File tempCheck = new File (list.get(i).getBallotNumber()+".txt");
if(tempCheck.exists()){
Scanner inputFile = new Scanner(tempCheck);
for(int m = 0; m < list.get(i).getNumberOfChoices(); m++){
if(list.get(i).getVote().equals(list.get(i).getChoice(m))){
//outputFile.println(list.get(i).getChoice(m) + ":" + getInt(m, tempCheck) + 1);
inputFile.nextLine();
}
else{
outputFile.println(inputFile.nextLine());
}
}
}
else{
for(int a = 0; a < list.get(i).getNumberOfChoices(); a++){
if(list.get(i).getVote().equals(list.get(i).getChoice(a))){
outputFile.println(list.get(i).getChoice(a) + ":" + "1");
}
else{
outputFile.println(list.get(i).getChoice(a) + ":" + "0");
}
}
}
System.out.println("PHE");
outputFile.close();
File g = new File("temp2.txt");
File f = tempCheck;
f.delete();
g.renameTo(f);
}

Related

File.delete() isn't deleting the .Json file in Java

I am trying to delete a json file I just created, The file is in the same directory as the workplace so I didn't include it when creating the new File object.
I also closed the output stream before trying to delete the file by using .close() method.
import java.io.File;
public static void processFilesForValidation(String name, Scanner obj, PrintWriter logFile) {
int count = 0;
PrintWriter outputStream = null;
String[] line = obj.nextLine().split(",", -1);
if (count == 0) {
for (int i = 0; i < line.length; i++) {
try {
if (line[i].equals(" ")) {
throw new CSVFileInvalidException();
} else {
try {
outputStream = new PrintWriter((new FileOutputStream(name + ".json", true)));
} catch (FileNotFoundException e) {
System.out.println("Could not create json file " + name
+ ". Program will terminate after deleting any corrupted files and closing any opened files.");
obj.close();
outputStream.close();
String fname = name + ".json";
File file = new File(fname);
file.delete();
System.exit(0);
}
}
} catch (CSVFileInvalidException eCsvFileInvalidException) {
System.out.println(
"File " + name + ".CSV is invlaid: field is missing. \nFile is not converted to JSON.");
int detected = line.length - 1;
logFile.println("\nFile " + name + ".CSV is invalid. \nMissing field:" + detected
+ " detected, 1 missing");
for (int j = 0; j < line.length; j++) {
if (line[j].equals(" ")) {
logFile.print(line[j] + "***, ");
} else {
logFile.print(line[j] + ", ");
}
}
logFile.close();
outputStream.close();
String fname= name+".JSON";
File file = new File(fname);
file.delete();
break;
}
}
}
}
The code is a little long but this is the method, I hope you can help me.
You open a new outputStream every time around the loop. As far as I can tell, you only close it on a couple of errors. So, on loop #2, the first outputStream is left dangling and not closed.

Writer dont writing in file but only create it

Im working on converter. I load file, start reading date from it and creating directories by year, month and day(+ another one dir) in witch ends are those converted text files. Everything is fine while creating those directories but in text files is nothing or only chunk of it.
public static void convertFile(File fileToConvert, File whereToSave, long shift) {
BufferedReader reader = null;
BufferedWriter writer = null;
String oldDate = "";
String newDate = "";
boolean boolDate = true;
try {
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
boolean block = true;
String line = "";
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (lineCounter==0) {
block = true;
} else {
block = false;
}
line = line.replaceAll("[^0-9-,:+NaN.]", "");
String[] data = line.split(",");
if (block) {
data[0] = data[0].substring(0, 10) + " " + data[0].substring(10);
data[0] = SimulatorForRealData.timeShift(data[0], shift);
// ====================================================================================
newDate = data[0].substring(0, 4) + " " + data[0].substring(5, 7) + " "
+ data[0].substring(8, 10);
String savingIn = SimulatorForRealData.createDirs(whereToSave.toString(),
data[0].substring(0, 4), data[0].substring(5, 7), data[0].substring(8, 10));
File f = new File(savingIn + "\\" + FILE_NAME + ".log");
if (!newDate.equals(oldDate) && boolDate == false) {
writer.close();
boolDate = true;
} else {
oldDate = newDate;
boolDate = false;
}
writer = new BufferedWriter(new FileWriter(f));
// =====================================================================================
writer.write("<in date=\"" + data[0].substring(0, 10) + "T" + data[0].substring(11)
+ "\" t=\"1\" >\n");
writer.write(data[0] + "\n");
writer.write(0 + " " + 0 + " " + 0 + "\n");
for (int x = 0; x <= 10; x++) {
writer.write("NaN" + " ");
}
writer.write("\n");
for (String s : data) {
if (s.equals(data[0])) {
continue;
}
writer.write(s + ";");
}
writer.write("\n");
} else {
for (String s : data) {
writer.write(s + ";");
}
writer.write("\n");
}
lineCounter++;
if (lineCounter == 118) {
lineCounter = 0;
writer.write("</in>\n\n");
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is method where i perform it. Can someone help me. I tried different "writers" and nothing. I have suspicious that it will be problem in closing file but i dont know for sure.
I think you should close every writer you created, not only last one.
for (File file : fileToConvert.listFiles()) {
reader = new BufferedReader(new FileReader(file));
...
writer = new BufferedWriter(new FileWriter(f));
while ((line = reader.readLine()) != null) {
....
}
writer.close();
}
writer flushes all changes on disk only when buffer is overflowed or it is closed.
I see two main problems:
You create a file every time you read a line. You should put it outside the loop (or loops, if you want only one file)
Always data is written with the same filename. It should have different filenames if you make a file for every file read.

Java - .csv file as input

My program stimulates FCFS scheduling algorithm. It takes a .csv file as input and output the average waiting time. I have trouble with inputting the file. This is the error that i get when i ran the code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at main.FCFS.main(FCFS.java:16)
What am I doing wrong? I cannot seems to figure it out. Please help.
package main;
//programming FCFS scheduling algorithm
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
public class FCFS {
public static void main(String[] args) throws FileNotFoundException {
// To Store Name of the file to be opened
String file = args[0];
int i = 0, n;
double AWT = 0, ATT = 0;
int AT[] = new int[100];
int BT[] = new int[100];
int WT[] = new int[100];
int TAT[] = new int[100];
int PID[] = new int[100];
// To open file in read mode
FileInputStream fin = null;
// To read input(file name) from standard input stream
Scanner s = new Scanner(new File("/Users/SLO/ex.csv"));
// To hold each single record obtained from CSV file
String oneRecord = "";
try {
// Open the CSV file for reading
fin = new FileInputStream(file);
// To read from CSV file
s = new Scanner(fin);
// Loop until all the records in CSV file are read
while (s.hasNextLine()) {
oneRecord = s.nextLine();
// Split record into fields using comma as separator
String[] details = oneRecord.split(",");
PID[i] = Integer.parseInt(details[0]);
AT[i] = Integer.parseInt(details[1]);
BT[i] = Integer.parseInt(details[2]);
System.out.printf("Process Id=%d\tArrival Time=%d\tBurst Time=%d\n", PID[i], AT[i], BT[i]);
i++;
}
WT[0] = 0;
for (n = 1; n < i; n++) {
WT[n] = WT[n - 1] + BT[n - 1];
WT[n] = WT[n] - AT[n];
}
for (n = 0; n < i; n++) {
TAT[n] = WT[n] + BT[n];
AWT = AWT + WT[n];
ATT = ATT + TAT[n];
}
System.out.println(" PROCESS BT WT TAT ");
for (n = 0; n < i; n++) {
System.out.println(" " + PID[n] + " " + BT[n] + " " + WT[n] + " " + TAT[n]);
}
System.out.println("Avg waiting time=" + AWT / i);
System.out.println("Avg waiting time=" + ATT / i);
} catch (FileNotFoundException e) {
System.out.printf("There is no CSV file with the name %s", file);
}
finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Well, an ArrayIndexOutOfBoundsException is thrown if there are no arguments, because you access the empty array at a non existing index. Add the following lines to check if the argument is passed correctly:
...
public static void main(String[] args) throws FileNotFoundException {
if (args.length == 0)
throw new IllegalArgumentException("Missing mandatory file name in argument list");
// To Store Name of the file to be opened
String file = args[0];
...
If the missing argument ist the reason for the failure, check out https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html to find out how to pass it properly.

How can I write all the pages in the text document

I am trying to write extracted text of the pdf file into text document but currently, only the first page is being written in the text document although 6 pages are being output in the console of eclipse.
How can I fix that?
I appreciate any help.
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
int pagenumber = reader.getNumberOfPages();
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
for (String s : line.split("\n")) {
out.println(s);
}
out.close();
System.out.println(line);
}
Try moving the instantiation and closing of the PrintWriter outside of the main for loop:
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
int pagenumber = reader.getNumberOfPages();
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
for (String s : line.split("\n")) {
out.println(s);
}
System.out.println(line);
}
out.close();
I'm not sure if that'll do the trick but it may help as the PrintWriterkeeps opening and closing every page.
Try to use your output variable out of loop, maybe helps
try {
PdfReader reader = new PdfReader("D:\\hl_sv\\L09MF.pdf");
PrintWriter out = new PrintWriter("D:\\hl_sv\\L09MF.txt");
int pagenumber = reader.getNumberOfPages();
for (int i = 1; i <= pagenumber; i++) {
System.out.println("==================PAGE NUMBER " + i
+ "===================");
String line = PdfTextExtractor.getTextFromPage(reader, i);
for (String s : line.split("\n")) {
out.println(s);
}
System.out.println(line);
}
out.close();

how to output file lists to text file using java

hello i am a newbie to java. i just started learning java last week.
below is a code I am using to display all files and the corresponding file sizes of a folder and it's subfolder.
However, instead of displaying the output in the Eclipse console, what I need to achieve is actually output the same data to a text file. I've been searching on the net on how to accomplish this over the last couple of days but I wasn't able to come to a solution.
Can someone advise me on what code to use to accomplish my task?
Thanks so much!
public class ReadFile1 {
public static void main(String[] a)throws IOException{
showDir(1, new File("/Users/User/Documents/1 eclipse test/testfolder1"));
//File file = new File("/Users/User/Documents/1 eclipse test/testfolder1/puppy4.txt");
//long fileSize = file.length();
}
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++)
System.out.print('-');
System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}
Here is your example converted :
public class ReadFile1
{
public static void main(String[] a) throws IOException
{
FileWriter fstream = new FileWriter("C:\\test.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
showDir(out,1,new File("C:\\"));
out.flush();
out.close();
}
static void showDir(BufferedWriter writer, int indent, File file) throws IOException
{
for(int i = 0; i < indent; i++)
{
writer.write('-');
//System.out.print('-');
}
writer.write(file.getName() + " - " + file.length() / 1024 + " KB");
writer.newLine();
//System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if(file.isDirectory())
{
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++)
{
showDir(writer,indent + 4, files[i]);
}
}
}
}
Update your showDir with the file writing code as mentioned here:
File file = new File("info.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
PrintWriter writer = new PrintWriter(file);
writer.println(file.getName() + " - " + file.length() / 1024 + " KB");
writer.close();
This will put the console output into the text file:
try{
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}catch(SecurityException se){
//Exception handling
}
setOut(PrintStream out) reassigns the "standard" output stream.It throws SecurityException -- if a security manager exists and its checkPermission method doesn't allow reassigning of the standard output stream.

Categories

Resources