I'm currently testing the edit method for the CSV file. However, the File.Delete() and File.Rename() is highlighting in yellow and told me that these commands will be ignored. What is the cause of this and how do I fix it?
public class Main {
private static Scanner x;
public static void main(String[] args) {
String filepath = "Leads.csv";
String editerm = "Lead_000";
String newID = "Lead_003";
String newname = "Cac";
}
public static void editRecord(String filepath, String editerm, String newID, String newname) {
String tempfile = "temp.csv;";
File oldfile = new File(filepath);
File newfile = new File(tempfile);
String ID = "";
String name = "";
try {
FileWriter fw = new FileWriter(tempfile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
ID = x.next();
name = x.next();
if (ID.equals(editerm)) {
pw.println(newID + "," + newname);
} else {
pw.println(ID + "," + name);
}
x.close();
pw.flush();
pw.close();
oldfile.delete();
File dump = new File(filepath);
newfile.renameTo(dump);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guess that IDE marks your File.Delete() and File.Rename() lines.
It says that it will ignore the result of this function because you don't store the return value.
If you want to fix it, you should store the return values
boolean result = oldfile.delete();
Related
i am creating temp file(outputFile) and writing text with BufferedWriter. i am not getting exception. But the String is not appended. I used sysout also for outputfile but it printing nothing.
File outputFile = File.createTempFile("abc",".tmp");
ArrayList<LoadDirectoryResponse> dirlist = new ArrayList<LoadDirectoryResponse>();
ArrayList<LoadDirectoryResponse> dirlistReq = new ArrayList<LoadDirectoryResponse>();
filenames = filenames.substring(0, filenames.length()-1);
String[] finalFileName = filenames.split(",");
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
for(MultipartFile multifile : files)
{
String fileName = multifile.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
File file = null;
file = File.createTempFile(fileName, prefix);
multifile.transferTo(file);
for(LoadDirectoryResponse obj: dirlistReq )
{
if(fileName.equals(obj.getFilename()))
{
LoadDirectoryResponse objRes = new LoadDirectoryResponse(obj.getFilename(),obj.getKeyWord(),obj.getLinesToBeCopied(),obj.isChecked());
Scanner sc = new Scanner(file);
if(obj.isChecked()) {
BufferedWriter br = new BufferedWriter(new FileWriter(outputFile));
ArrayList<String> linesToBeAdd = new ArrayList<String>();
int i = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
linesToBeAdd.add(line);
if(line.contains(obj.getKeyWord()))
{
String value = DataQuestService.getLinesToBeAdd(i,linesToBeAdd,lines);
br.write(value);
break;
}
else
{
objRes.setStatus("Not Found");
}
}
}
dirlist.add(objRes);
}
}
}
Scanner sc1 = new Scanner(outputFile);
while(sc1.hasNextLine())
{
System.out.println(sc1.nextLine());
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + outputFile.getName() + "\"")
.body(outputFile);
}
Please help with this
Thanks in Advance
When use the BufferedWriter you need to flush and close the writer.
You can use the try-with-resources in Java7+.
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
// write something...
}
In this case, I recommend moving the BufferedWriter outside. Because you just output many files to temporary files.
// Your code ...
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
for(MultipartFile multifile : files) {
String fileName = multifile.getOriginalFilename();
// Your code ...
}
}
// Your code ...
copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
I am traversing to the below location to the properties file : "global.properties"
String currentPath = System.getProperty("user.dir");
File appPropDir = new File(currentPath, "properties");
File app_prop_file = new File(appPropDir, "global.properties");
After making changes to a particular parameter in "global.properties", I want to know how to upload the file to the same location. For instance, here I am appending the "propFileName" to the end of property : product + ".app.product.types". After making this append, how to upload the file "global.properties" to the user.dir
Entire code :
public static synchronized void updateGlobalPropFile(String product_name, String file_name) throws Exception {
// logger.debug("Entry-->
// com.manh.ci.eaas.util.TemplateUtil.updateGlobalPropFile");
System.out.println("in updateGlobalPropFile");
String downloadLoc = "";
String mmcType;
String vers;
String box, userId, password, location, key;
int port;
port = 22;
String currentPath = System.getProperty("user.dir");
File appPropDir = new File(currentPath, "properties");
File app_prop_file = new File(appPropDir, "global.properties");
downloadLoc = app_prop_file.toString();
port = Integer.parseInt(prop.getProperty("ssh_connection_port"));
port = 22;
String product = product_name;
String file = file_name;
String propFileName = "file";
String changeKey = product + ".app.product.types";
System.out.println("changeKey>>" + changeKey);
// download global.properties instead of using local copy
String globalPropFileLoc = downloadLoc;
try (BufferedReader br =
new BufferedReader(new InputStreamReader(new FileInputStream(new File(globalPropFileLoc))))) {
ArrayList<String> lines = new ArrayList<String>();
String line = "";
String tempLine = "";
while ((line = br.readLine()) != null) {
if (line.startsWith(changeKey) && line.contains(changeKey) &&
(line.substring(0, changeKey.length()).equals(changeKey))) {
String strChangeKey = line.substring(changeKey.length() + 1);
// System.out.println("strChangeKey>>"+strChangeKey);
if (strChangeKey.equalsIgnoreCase("") || strChangeKey.equalsIgnoreCase(" ")) {
// chek if value after = is empty for a newly added changekey : don't add comma
// for first value
tempLine = line + propFileName;
} else {
tempLine = line + "," + propFileName;
}
} else {
tempLine = line;
}
lines.add(tempLine);
}
if (lines.size() != 0) {
BufferedWriter out = new BufferedWriter(new FileWriter(new File(globalPropFileLoc)));
String finalStr = "";
for (int i = 0; i < lines.size(); i++) {
finalStr = finalStr + lines.get(i) + "\n";
}
out.write(finalStr);
System.out.println("updated global prop file");
out.close();
}
uploadFile();
} catch (Exception e) {
// logger.debug(e);
e.printStackTrace();
throw e;
}
}
Just help me with the uploadFile(); in the above code. Thanks a lot.
This should do the trick:
public void uploadFile(final List<String> lines, final String targetFilePath) throws IOException {
Files.write(Paths.get(targetFilePath), lines);
}
My program is basically a user's name, and balance, this is stored in a file, when the user updates their profile, I want their balance to update too, but not their name, as they already have it in the file.
The name and balance are split with a comma. In the file it is displayed like this:
Stacey,0.02
(The name is actually a randomly generated number+letter string, but I thought I'd keep it simple here.)
When I try to write to the file with this code, it doesn't write anything.
Code:
btnSaveUserid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = txtUserid.getText().toString();
String balance = beedcoin1Balance.getText().toString();
File file = new File("d:/users/joel/desktop/code/usersid.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("d:/users/joel/desktop/code/usersid.txt"));
List<String> terms = new ArrayList<String>();
List<String> ttlBalance = new ArrayList<String>();
while ((sCurrentLine = br.readLine()) != null) {
String[] ar = sCurrentLine.split(",");
String userid = ar[0];
terms.add(userid);
System.out.println(terms);
}
if(terms.contains(text)) {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine());
String line = scanner.nextLine();
String[] ar = line.split(",");
String userid = ar[0];
String bdcv1val = ar[1];
int lineNum = 0;
lineNum++;
if(line.equals(userid)) {
Path path = Paths.get("d:/users/joel/desktop/code/usersid.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replace(txtUserid.toString(), txtUserid.toString());
Files.write(path, content.getBytes(charset));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
}
else {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
} catch (IOException el) {
el.printStackTrace();
} finally {
try {
if(br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It all takes place in a button's action listener, and this code outputs the "Successfully printed to file" but doesn't actually print it to the file. I'm honestly perplexed, any help would be greatly appreciated.
This program is almost done. But the problem is when I edit and put it in a temp file, both the edited and unedited values are written. So, the temp file gets another value (which is the replacement). I would also like to know if there are ways on how I could rename the temp file. I tried looking at other questions' answers but none of those solved my problem.
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String edit = "";
String edit2 = "";
String data = "";
Scanner scanner = new Scanner(nfile2);
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String _bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
while(scanner.hasNext()){
boolean replace = false;
String str = scanner.nextLine();
if((str.contains(_btitle))&&(str.contains(_bauthor)))
{
String conv = str.toString();
System.out.println("Search found");
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
edit = str.replaceAll(_btitle, btitle1);
edit2 = str.replaceAll(_bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
replace = true;
//System.out.println("" +edit + "" +edit2); Test output
}
else {
//System.out.println("" +str); Test output
tbw1.append(str);
tbw1.append("\n");
tbw2.write(str);
tbw2.newLine();
}
}
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
EDIT 1:
Okay. Figured out how to delete and rename. Problem is I have to edit 2 times before it's finally deleted and renamed. (I removed the author because there are problems with the output).
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line = "";
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
while((line = br2.readLine()) !=null){
String btitle1;
if(line.contains(_btitle))
{
String conv = line.toString();
System.out.println("Search found");
btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
tbw1.append(line.replaceAll("" +_btitle, "" +btitle1));
tbw1.append("\n");
tbw2.write(line.replaceAll("" +_btitle, "" +btitle1));
tbw2.newLine();
}
else {
tbw1.append(line);
tbw1.append("\n");
tbw2.write(line);
tbw2.newLine();
}
}
twriter.flush();
twriter2.flush();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}