public void newEditSportRecord(){
String filepath = "sport.txt"; //exists in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
String editTerm = JOptionPane.showInputDialog("Enter ID of Sport you wish to modify:");
String tempFile = "temp.txt"; // to be created in C:\Users\Dell\Documents\NetBeansProjects\Assignment\
File oldFile = new File(filepath);
System.out.println(oldFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\sport.txt
File newFile = new File(tempFile);
System.out.println(newFile.getAbsolutePath()); // prints C:\Users\Dell\Documents\NetBeansProjects\Assignment\temp.txt
String ID, name = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
while (x.hasNextLine()) {
ID = x.next();
System.out.println(ID);
name = x.next();
System.out.println(name);
if (ID.equals(editTerm)) {
newID = JOptionPane.showInputDialog("Enter new Sport ID:");
newName = JOptionPane.showInputDialog("Enter new Sport Name:");
pw.println(newID);
pw.println(newName);
pw.println();
JOptionPane.showMessageDialog(modifySport, "Record Modified");
} else {
pw.println(ID);
pw.println(name);
pw.println();
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception ex) {
JOptionPane.showMessageDialog(modifySport, ex);
}
}
I have the following function to try and modify a text file. However, it does NOT delete the original file "sport.txt" nor does it rename "temp.txt" to "sport.txt". It DOES read from the file and create a copy of "sport.txt" with all the relevant modifications as "temp.txt". I had suspected it was a problem with the writers but having closed all of them, the issue still persists. Is this simply down to permission problems as the folder exists in the Documents folder on Local Disk?
Yes, it is a permission problem. Either change the permission of the Documents folder and give access to all the permissions to your user or change your working folder.
Related
I want to create String to txt file that i got from textfield. the file created but it's always empty. i don't know what is wrong. it's work if i manually write the string : out.write("text"), but when i took the text from textview, it's always empty. please help.
this is code to created file :
String fname = t2.getText().toString()+".txt";
String text = t3.getText().toString();
String fpath = t.getText().toString();
try {
File root = new File(fpath);
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fname);
FileWriter writer = new FileWriter(gpxfile);
PrintWriter out = new PrintWriter(writer);
out.println(text);
out.flush();
out.close();
Toast.makeText(getBaseContext(), "Berhasil menyimpan", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
break;
this is where text = t3.getText().toString() came from :
t3 = (TextView)findViewById(R.id.saveText);
I have this code
public User createnewproflie() throws IOException
{
FileWriter fwriter = new FileWriter("users.txt",true); //creates new obj that permits to append text to existing file
PrintWriter userfile = new PrintWriter(fwriter); //creates new obj that prints appending to file as the arg of the obj is a pointer(?) to the obj that permits to append
String filename= "users.txt";
Scanner userFile = new Scanner(filename); //creates new obj that reads from file
User usr=new User(); //creates new user istance
String usrname = JOptionPane.showInputDialog("Please enter user name: "); //acquires usrname
userfile.println("USER: "+usrname+"\nHIGHSCORE: 0\nLASTPLAY: 0"); //writes usrname in file
userfile.flush();
usr.setName(usrname); //gives usr the selected usname
return usr;
}
and it doesn't output on the file... can someone help please?
i knew that flush would output all of the buffered text but it doesn't seem to work for some strange reason...
You can use a String with a FileWriter but a Scanner(String) produces values scanned from the specified string (not from a File). Pass a File to the Scanner constructor (and it's a good idea to pass the same File to your FileWriter). And you need to close() it before you can read it; maybe with a try-with-resources
File f = new File("users.txt");
try (FileWriter fwriter = new FileWriter(f,true);
PrintWriter userfile = new PrintWriter(fwriter);) {
// ... Write stuff to userfile
} catch (Exception e) {
e.printStackTrace();
}
Scanner userFile = new Scanner(f);
Finally, I usually prefer something like File f = new File(System.getProperty("user.home"), "users.txt"); so that the file is saved in the user home directory.
Below is the code to read the file from the server. I Want to read & convert the file dynamically (not hard coded )into different file format(CSV). Could anyone please guide me to capture the uploaded file name dynamically.
try
{
//creating File instance to reference text file in Java
String str1=null;
String str2=null;
String str3=null;
int cnt=0,len1=0,len2=0;
File text = new File("C:\\Petty Ascii Detail.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
File file = new File("C:\\Test\\Write1.txt");
//if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine())
{
String line = scnr.nextLine();
cnt=line.length();
for(int i=0;i<3;i++)
{
if (Character.isDigit(line.charAt(i)))
str1=line;
else
str2=line;
}
len1=str1.length();
len2=str2.length();
if(len1!=len2)
{
str3=str1+str2;
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(str3);
bw.newLine();
System.out.println("Done");
bw.close();
}
lineNumber++;
}
}
catch (IOException e)
{
e.printStackTrace();
}
Any suggestions are really appreciated.
Thanks,
Balaji
Just started coding and found my self overwhelmed with different types of writing to a file. I'm using File and PrintStream library. My issue is that after user is done with typing notes and reopens the file, the file is overwritten. I wish to add just a nextLine function so when the file is opened again we just add text to line2. Thank you in advance.
This is my piece of code:
if(userOption.equals("open") || userOption.equals("OPEN") ){
System.out.print("Please enter the name of the file you want to open : ");
fileNameOpen = kybd.nextLine();
File input = new File( fileNameOpen );
PrintStream print = new PrintStream( input );
System.out.print("Now you can start typing your notes: ");
// print.println(userNotes = kybd.nextLine());
print.println(userNotes = kybd.nextLine());
print.close();
}//end of if
If you just want something simple, this will work:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileNameOpen , true)));
userNotes = kybd.nextLine()
out.println(userNotes);
out.close();
} catch (IOException e) {
//oh noes!
}
The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).
Of course you will need to incorporate this into your logic.
PrintWriter out = new PrintWriter(
new BufferedWriter(new FileWriter(fileNameOpen, true)));
The second argument in the FileWriter will allow you to append a line
if(userOption.equals("open") || userOption.equals("OPEN") ){
System.out.print("Please enter the name of the file you want to open : ");
Scanner kybd = new Scanner(System.in);
String fileNameOpen = kybd.next();
kybd.nextLine();
try{
String data = " This content will append to the end of the file";
File file = new File(fileNameOpen);
// if file does not exist create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fWriter = new FileWriter(file.getName(),true);
BufferedWriter writer = new BufferedWriter(fWriter);
writer.write(data);
writer.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}//end of if
I am saving to a file a double list (mydata) which is some data the user enters and a string list (dates_Strings) which is the current date.
The user enters some data and pressing a 'save' button , I save the data and the currents date.
So , user may enter "1" and press save (1, 08/05/13)
enter "2" and press save (2, 08/05/13).
Because the user may enter data during a day (same date) I don't want to save many instances of the date.I want to save all the user data in that date.
I tried sth like:
for (int i=1;i<mydata.size();i++){
bw.write(mydata.get(i)+",");
while (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(dates_Strings.get(i)+"\n");
}
but it saves only the last entered data.
I am saving as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
FileOutputStream fos;
//saving them
try {
fos = new FileOutputStream(file,true); //true in order to append
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i=1;i<mydata.size();i++){
//if (!(dates_Strings.get(i).equals(dates_Strings.get(i-1))))
bw.write(mydata.get(i)+","+dates_Strings.get(i)+"\n");
}
value.setText("");
bw.flush();
bw.close();
} catch (IOException e2) {
e2.printStackTrace();
}//catch
}
I am loading as:
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
String s;
FileInputStream fis;
try {
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
do {
s = br.readLine();
if (s != null ){
String[] splitLine = s.split(",");
mydata.add(Double.parseDouble(splitLine[0]));
//dates_Strings.add(thedate.parse(splitLine[1]));
dates_Strings.add(splitLine[1]);
}
} while (s != null );
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Mmmm... maybe this can help you, basic idea as mentioned by our colleagues: receive input, save it in file, receive new input, read the existing file before, add the new content to the old content and save the updated content of your file.
//Asumming your values are these:
List<String> datesList = new ArrayList<String>();
List<Double> dataList = new ArrayList<Double>();
//You must fill your data of course...
//I use a buffer to put in order my data
StringBuffer stringAppender = new StringBuffer();
for (int i = 0; i < dataList.size(); i++) {
stringAppender.append(dataList.get(i));
stringAppender.append(",");
stringAppender.append(datesList.get(i));
if (i != dataList.size()-1) {
stringAppender.append("\n");
}
}
//I use the Buffered Writer and then save all the data ordered in one single String.
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw.write(stringAppender.toString());
bw.close();
Then... you have new inputs right?
//I read my file first
BufferedReader br = new BufferedReader(new FileReader(new File("/home/mtataje/saved.txt")));
String line;
StringBuffer auxBuffer = new StringBuffer();
while ((line = br.readLine()) != null) {
auxBuffer.append(line);
auxBuffer.append("\n");
}
//Then append to the StringBuffer again, but your StringBuffer has data saved inside :)
for (int i = 0; i < newDataListIncoming.size(); i++) {
auxBuffer.append(newDataListIncoming.get(i));
auxBuffer.append(",");
auxBuffer.append(newDatesIncoming.get(i));
if (i != newDataListIncoming.size()-1) {
auxBuffer.append("\n");
}
}
//And write your file
BufferedWriter bw2 = new BufferedWriter(new FileWriter(new File("/home/mtataje/saved.txt")));
bw2.write(auxBuffer.toString());
bw2.close();
Of course, you will use methods and not use redundancy in your code as me, I hope I gave you a hand with this. Best regards.
You must load the previous value in your file .. read it and add new value .. then save it !