How to delete and override a file in java? - java

I want to rename and delete "products2.txt" to "products.txt".
if I test with another files "test1" and "test2", in the same directory, will work fine, but with my filles "products" and "products2", doesn't work, not even to delete the file with file.delete();
try{
File file = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products.txt");
Scanner sc = new Scanner(file);
File tempFile = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products2.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
System.out.println("ID number:");
int delete = in.nextInt();
String lineToRemove = Objects.toString(delete,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" ");
String part1 = trimmLine[0];
if(!part1.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.flush();
writer.close();
reader.close();
sc.close();
file.delete();
tempFile.renameTo(file);
}catch (IOException e){
e.printStackTrace();
}

Related

How can I add a code that prints when record is deleted successfully or invalid if they enter other number not in txt file?

Any idea on How I can check if A record is deleted or is there a better way to delete an array of code using bufferedreader and writter?
public static void DeleteData() throws IOException {
try {
Viewrecord();
Scanner strInput = new Scanner(System.in);
String ID, record;
File tempDB = new File("tempdata.txt");
File db = new File("Database.txt");
BufferedReader br = new BufferedReader(new FileReader(db));
BufferedWriter bw = new BufferedWriter(new FileWriter(tempDB));
System.out.println("\t\t Delete An Item \n");
System.out.println("Enter Item ID: ");
ID = strInput.nextLine();
while ((record = br.readLine()) != null) {
String[] data = record.split(":::");
if (data[0].toString().equals(ID))
continue;
{
bw.write(record);
bw.flush();
bw.newLine();
}
}
br.close();
bw.close();
db.delete();
tempDB.renameTo(db);
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
I did try using a boolean inside the while loop

Java append new column to csv file

I want to calculate some column data and write it to csv file as column. Then after calculating other column of data I want to append it to same file but as new column.
Here is what I did:
try {
FileWriter writer = new FileWriter(OUT_FILE_PATH, true);
for (int i=0; i<data.size(); i++) {
writer.append(String.valueOf(data.get(i)));
writer.append(",");
writer.append("\n");
}
writer.flush();
writer.close();
} catch (Exception e) {}
Result - It appends the new column below the first column, so I have single long column.
Thanks,
Something like this perhaps:
public void appendCol(String fileName, ???ArrayList??? data) { //assuming data is of type ArrayList here, you need to be more explicit when posting code
String lineSep = System.getProperty("line.separator");
String output = "";
try{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
output += line.replace(
lineSep,
"," + String.valueOf(data.get(i)) + lineSep);
i++;
}
br.close();
FileWriter fw = new FileWriter(fileName, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
} catch (Exception e){
e.printStackTrace();
}
}
You will have to read your file (line by line) and then insert the new column to every line. Here's a solution using BufferedReader and BufferedWriter
public void addColumn(String path,String fileName) throws IOException{
BufferedReader br=null;
BufferedWriter bw=null;
final String lineSep=System.getProperty("line.separator");
try {
File file = new File(path, fileName);
File file2 = new File(path, fileName+".1");//so the
//names don't conflict or just use different folders
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line = null;
int i=0;
for ( line = br.readLine(); line != null; line = br.readLine(),i++)
{
String addedColumn = String.valueOf(data.get(i));
bw.write(line+addedColumn+lineSep);
}
}catch(Exception e){
System.out.println(e);
}finally {
if(br!=null)
br.close();
if(bw!=null)
bw.close();
}
}
I have used apache-commons for resolving this issue. There was no perfect answer that worked for me. After a lot of effort, this worked for me.
Writer writer = Files.newBufferedWriter(Paths.get("output.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//add whichever column you want in withHeader
.withHeader("createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location", "consumption"));
//actual columns in your passed CSV
String[] HEADERS = {"createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location"};
Reader in = new FileReader(yourCsvFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord row : records) {
String tempValue = String.valueOf(Long.parseLong(row.get("leaveTs")) - Long.parseLong(row.get("joinTs")));
csvPrinter.printRecord(row.get("createdTs"), row.get("destroyedTs"),row.get("channelName"), row.get("uid"),
row.get("suid"), row.get("did"), row.get("joinTs"), row.get("leaveTs"),
row.get("platform"), row.get("location"), tempValue);
}
Hope this will help you.
{
//CREATE CSV FILE
StringBuffer csvReport = new StringBuffer();
csvReport.append("header1,Header2,Header3\n");
csvReport.append(value1 + "," + value2 + "," + value3 + "\n");
generateCSVFile( filepath,fileName, csvReport); // Call the implemented mathod
}
public void generateCSVFile(String filepath,String fileName,StringBuffer result)
{
try{
FileOutputStream fop = new FileOutputStream(filepath);
// get the content in bytes
byte[] contentInBytes = result.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
//wb.write(fileOut);
if(fop != null)
fop.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
}

Deleting File and Renaming file in java

i am trying to use this code to replace field and after the replace is done i like to delete the file. But when i replace the file only 1 line was saved. How should i ensure that the other lines will be saved?
public static void main(String[] args){
AddChips();
}
public static void AddChips() {
File oldFile = new File ("players.dat");
File newFile = new File ("tempchips.dat");
BufferedReader br = null;
BufferedWriter bw = null;
ArrayList<String> player = new ArrayList<String>();
try {
br = new BufferedReader(new FileReader(oldFile));
bw = new BufferedWriter(new FileWriter(newFile));
String line;
Scanner read = new Scanner(System.in);
System.out.println("Please Enter Username");
String UserN = read.nextLine();
System.out.println("Please Enter Chips to Add");
String UserCadd = read.nextLine();
while ((line = br.readLine()) != null) {
String[] details = line.split("\\|");
String Username = details[0];
String Password = details[1];
String Chips = details[2];
int totalChips = (Integer.parseInt(UserCadd)+ Integer.parseInt(Chips));
if (Username.equals(UserN)){
line = Username + "|" + Password + "|" + totalChips;
bw.write(line + System.getProperty("line.separator"));
}
//issue is here
br.close();
bw.close();
oldFile.delete();
newFile.renameTo(oldFile);
//AdminMenu();
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
}

How can i split a textfile and store 2 values in one line?

I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Text File error Scanner

I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work
public static void Option2Method() throws IOException
{
File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
Scanner writer =new Scanner(tempFile);
String currentLine;
while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.
Example:
public static void Option2Method() throws IOException {
File inputFile = new File("wordlist.txt");
FileWriter fstream = new FileWriter("TempWordlist.txt", true);
BufferedWriter writer = new BufferedWriter(fstream);
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.write(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Using PrintWriter:
File inputFile = new File("wordlist.txt");
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.print(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Scanner doesn't have a print method. It is used to scan a file and read data from it.
If you want to write to a file, use this or that or just google "java write to file"

Categories