Renaming file to existing file java - java

I am trying to
Create Temp File "Temp Account Info.txt"
Write information from existing Account File "Account Information.txt" TO "Temp Account Info.txt"
Omit certain information
Delete "Account Information.txt"
Rename "Temp Account Info.txt" to "Account Information.txt"
My issue is steps 4 and 5. Nor am I sure if I am ordering it correctly.
The code is provided below.
public static void deleteAccount(String accountNumber) throws Exception {
File accountFile = new File("Account Information.txt");
File tempFile = new File("Temp Account Info.txt");
BufferedReader br = new BufferedReader(new FileReader(accountFile));
FileWriter tempFw = new FileWriter(tempFile, true);
PrintWriter tempPw = new PrintWriter(tempFw);
String line;
try {
while ((line = br.readLine()) != null) {
if(!line.contains(accountNumber)) {
tempPw.print(line);
tempPw.print("\r\n");
}
}
**FileWriter fw = new FileWriter(accountFile);
PrintWriter pw = new PrintWriter(fw);
tempFile.renameTo(accountFile);
accountFile.delete();
fw.close();
pw.close();
tempFw.close();
tempPw.close();
} catch (Exception e) {
System.out.println("ERROR: Account Not Found!");
}
}
The full code can be found at: https://hastebin.com/eposapecep.java
Any help would be greatly appreciated!
I am aware that I do not correctly check for "Account Not Found" and will try to figure this out after the naming issue.
Thanks in advance!

Use the renameTo() method of File.
try {
File file = new File("info.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String str = br.readLine();
File file2 = new File("temp.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(file2));
bw.write(str);
br.close();
bw.close();
if (!file.delete()) {
System.out.println("delete failed");
}
if (!file2.renameTo(file)) {
System.out.println("rename failed");
}
} catch (IOException ex) {
ex.printStackTrace();
}
The code above reads the first line of info.txt, writes it to temp.txt, deletes info.txt, renames temp.txt to info.txt

Related

records not written line by line using csvwriter in java

I am using CSVWriter where all the records are written in a single line of text file. please help me in correcting the mistakes in my code.
public void parseWritefile()
{
try{
File file = new File("config.properties");
FileInputStream fileinput = new FileInputStream(file);
Properties prop = new Properties();
prop.load(fileinput);
newfile = prop.getProperty("newfile");
delimit = prop.getProperty("delimiter");
delimiter = delimit.charAt(0);
fileinput.close();
Compare Writefile = new Compare();
List<String[]> fnllist = Writefile.comparecollec();
CSVWriter writer=new CSVWriter(new FileWriter(newfile),delimiter,'"',"\n");
log.debug("Records are written");
writer.writeAll(fnllist);
writer.close();
}
catch (FileNotFoundException e)
{
log.error("File not found");
}
catch (IOException e)
{
log.error("IO exception");
}
}
Thanks,

Java getting id from csv file to combo box

I am have a program were there are two forms one for the consultant and for the customer. On the first form the user will enter the consultant details and his ID will be saved in a csv file and this works fine.
Consultant cons_save = new Consultant();
cons_save.setPersonfirstname(this.jTextField1.getText());
cons_save.setPersonlastname(this.jTextField2.getText());
cons_save.setPersonID(this.jTextField4.getText());
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
cons_save.ConsultantID = cons_save.PersonID;
cons_save.setConsultantID(this.jTextField4.getText());
this.jTextField4.setText("");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter("E:\\ryan_assignment_sit2\\ConsID\\consID.csv", true));
writer.append(cons_save.ConsultantID);
writer.append(",");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
cons_save.savecons();
After the id is saved the Id is called out from the csv to an array and this works fine as well.
public CreateCustomer() {
initComponents();
ArrayList<String> ConsIDList = new ArrayList<String>();
String csvFileToRead = "E:\\ryan_assignment_sit2\\ConsID\\consID.csv"; // Reads the CSV File.
BufferedReader br = null; // Creates a buffer reader.
String line = "";
String splitBy = ","; // Reader Delimiter
try {
br = new BufferedReader(new FileReader(csvFileToRead)); // Buffer Reader with file name to read.
Scanner reader = new Scanner(System.in);
while ((line = br.readLine()) != null) { //While there is a line to read.
reader = new Scanner(line);
reader.useDelimiter(splitBy);
while (reader.hasNext()) { // While there is a next value (token).
ConsIDList.add(reader.next());
}
}
} catch (FileNotFoundException exception) { // Exception Handler if the File is not Found.
exception.printStackTrace();
} catch (IOException exception) { // Input/Output exception
exception.printStackTrace();
} finally {
if (br != null) {
try {
br.close(); // Close the Scanner.
} catch (IOException exception) {
exception.printStackTrace();
}
}
Vector<String> vectorData = new Vector<String>(ConsIDList);
DefaultComboBoxModel<String> comboBoxModel = new DefaultComboBoxModel<>(vectorData);
this.jComboBox1.setModel(comboBoxModel);
}
}
The array is working fine but the combo box is not getting populated with the arraylist.

Can't Read File After Building in java

hey guys i've this program to read a file
public static String readFileAsString(String filename){
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(filename));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
reader.close();
return sb.toString();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "File Not Found","ERROR",JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
and this is my constructor
public tsst() {
initComponents();
JOptionPane.showMessageDialog(null, readFileAsString("test.txt"),"Succes",JOptionPane.DEFAULT_OPTION);
}
and the file is in the application project if i run the file from Netbeans it's work normaly i got what i need but if i build the application so i got the JAR File and i run it i got Error FILE NOT FOUND
and the same in the Writing
public static void writeFile(String canonicalFilename, String text){
File file = new File (canonicalFilename);
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter(file));
out.write(text);
out.close();
} catch (IOException ex) {
Logger.getLogger(tsst.class.getName()).log(Level.SEVERE, null, ex);
}
}
Add this line in your readFileAsString method
System.out.println("Current Directory:"+ new File(".").getAbsolutePath());
That will tell you what your application's current directory is. Put your test.txt file in that same directory and you should be able to read it. I'd imagine the output would be different between Netbeans (where you know the file is expected) and when you run the Jar (which could be anywhere).

Android Java Read and Save data doesnt work

Hey I would like to save datas and then I would like to read them and put them in a EditText
speichern.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
save();
tv.setText("gespeichert");
}
});
private void save() {
try {
File myFile = new File("bla.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(string.toString() + "\n");
myOutWriter.append(string2.toString());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Gespeichert",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
private void read() {
int bla;
StringBuffer strInhalt = new StringBuffer("");
try {
FileInputStream in = openFileInput("bla.txt");
while( (bla = in.read()) != -1)
strInhalt.append((char)bla);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
What can i change?`
pelase help me
I'm usin eclipse
And i would like to safe the .txt not external.
I don't believe you are creating your file correctly:
File file = new File("test.txt");
file.createNewFile();
if(file.exists())
{
OutputStream fo = new FileOutputStream(file);
fo.write("Hello World");
fo.close();
System.out.println("file created: "+file);
url = upload.upload(file);
}
And to read this file:
try {
// open the file for reading
InputStream instream = openFileInput("test.txt");
// if file the available for reading
if (instream) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = buffreader.readLine())) {
// do something with the settings from the file
}
}
// close the file again
instream.close();
} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}
And don't forget to encapsulate code with a try-catch block to catch an IOException which is thrown from these objects.
EDIT
Add this to your manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
or...
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Hope that helps! :)

File read, changed but how to write out?

Ok, forgive my beginner-ness and please tell me how I can output my text from "before.txt" into a fresh new file called "after". Obviously I have altered the text along the way to make it lower-case and eliminate non alphabetic characters.
import java.io.*;
public class TextReader {
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile() throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write("before.txt");
output.close();
}
}
What about this
public void openFile() throws IOException {
try {
// Read in the file
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine = br.readLine();
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
br.close(); // Close br to prevent resource leak
writeFile(currentLine);
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}
public void writeFile(String text) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
output.write(text);
output.close();
}
}
Let me guess, is this a school assignment?
Try this:
public void ReadAndWrite() throws IOException {
try {
// Read in the file
BufferedWriter output = new BufferedWriter(new FileWriter("/WS3Ex3/after.txt"));
BufferedReader br = new BufferedReader(
new FileReader(
new File("before.txt")));
String currentLine;
while((currentLine = br.readLine()) != NULL){
currentLine = currentLine.toLowerCase();
currentLine = currentLine.replaceAll("[A-Z]", "");
output.write(currentLine);
}
br.close(); // Close br to prevent resource leak
output.close();
}
// Exception if the file is not in the path specified
catch (Exception e) {
System.out.println("Error: File not found");
}
}

Categories

Resources