Problem to write on txt file on specific line - java

Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman
After run my code I take this:
Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman
3,Maria,Oaka,Woman,2,3,1,3,4,6
But I want, if I search for ID=2 go to 2nd line and put the numbers, like that:
Student.txt
1,Giannis,Oreos,Man
2,Maria,Karra,Woman,2,3,1,3,4,6
3,Maria,Oaka,Woman
Code:
#FXML
TextField ID1,glossa,math,fis,xim,prog,gym;
#FXML
public void UseAddLesson() throws IOException{
Scanner x = new Scanner("src/inware/students.txt");
FileWriter fW = new FileWriter("src/inware/students.txt",true);
BufferedWriter bW = new BufferedWriter(fW);
boolean found= false;
while(!found){
String line = x.nextLine();
if(line.contains(ID1.getText())){
bW.write(","+glossa.getText()+",");
bW.write(math.getText()+",");
bW.write(fis.getText()+",");
bW.write(xim.getText()+",");
bW.write(prog.getText()+",");
bW.write(gym.getText());
System.out.println(line);
found= true;
}
}
bW.close();
fW.close();
x.close();
}

Do not attempt to read/write to the same file at the same time. You also cannot append/overwrite the structure of a text file requires all the text following the inserting point to be written at a different position.
I recommend creating a temporary file and replacing the old file with the new one you're done:
#FXML
public void UseAddLesson() throws IOException{
String searchText = ID1.getText();
Path p = Paths.get("src", "inware", "students.txt");
Path tempFile = Files.createTempFile(p.getParent(), "studentsTemp", ".txt");
try (BufferedReader reader = Files.newBufferedReader(p);
BufferedWriter writer = Files.newBufferedWriter(tempFile)) {
String line;
// copy everything until the id is found
while ((line = reader.readLine()) != null) {
writer.write(line);
if (line.contains(searchText)) {
writer.write(","+glossa.getText()+",");
writer.write(math.getText()+",");
writer.write(fis.getText()+",");
writer.write(xim.getText()+",");
writer.write(prog.getText()+",");
writer.write(gym.getText());
break;
}
writer.newLine();
}
// copy remaining lines
if (line != null) {
writer.newLine();
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
}
}
// copy new file & delete temporary file
Files.copy(tempFile, p, StandardCopyOption.REPLACE_EXISTING);
Files.delete(tempFile);
}
Note: If you distribute the app, probably the src directory will become unavailable.

Related

Android/java Cant read from .txt file in local storage

So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}

Somehow this method deletes my file content but for no apparent reason

If I didn't miss anything you should be able to run this code, just need a trace.log file in your project root folder.
I don't get what's happening. I just declare some readers / writers and try to read from the file. I get an instant null and the file seems to be empty. WHY?!
import java.io.*;
public class StubLogHandler {
private String name = "";
private String path = "";
public StubLogHandler (String filePath, String fileName) {
this.name = fileName;
this.path = filePath;
}
// THIS IS THE PESCKY BUGGER
public void testReadWrite() {
this.fixPath();
File file = new File (this.path+this.name);
try ( FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file);
BufferedReader reader = new BufferedReader(fileReader);
BufferedWriter writer = new BufferedWriter(fileWriter);) {
System.out.println("Works, I think.");
String line = "";
while (line != null) {
line = reader.readLine();
System.out.println(line);
// Should get a coupl'a lines, instead I get instant null
// Before you ask, no, the file is not initially empty
}
} catch (FileNotFoundException fnfe) {
System.out.println("File Not Found");
} catch (IOException ioe) {
System.out.println("Could not read or write to file");
}
}
private void fixPath () {
if (this.path.isEmpty())
return;
char lastChar = this.path.charAt(this.path.length()-1);
if (lastChar != '\\')
this.path += "\\"; // In case user forgets the final '\'
}
public String getAbsolutePath() {
this.fixPath();
return new File(this.path+this.name).getAbsolutePath();
}
}
public class Start {
public static void main (String[] args) {
Start.testStuff();
}
private static void testStuff() {
StubLogHandler log = new StubLogHandler("","trace.log");
System.out.println(log.getPath()+log.getName());
System.out.println(log.getAbsolutePath());
log.testReadWrite();
}
}
EDIT
Output:
trace.log
D:\Personal\Java\Workspaces\Default\Practice\trace.log
Works, I think.
null
Creating that writer:
try ( FileReader fileReader = new FileReader(file);
FileWriter fileWriter = new FileWriter(file); // here
will immediately truncate that file in preparation for writing. e.g.
File x = new File("X");
FileWriter fw = new FileWriter(x);
will immediately erase the contents of the pre-existing file X
Normal reading and separately writing to the same file does not work.
FileReader and FileWriter are already buffered I believe. I personally do not use them, as they use the default platform encoding, which is gives unportable data.
And then the end of file is indicated by readLine returning null, hence do:
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
// Should get a coupl'a lines, instead I get instant null
// Before you ask, no, the file is not initially empty
}
Maybe be you want do something like:
Path fpath = Paths.get(this.path+this.name);
List<String> lines = Files.readAllLines(fpath, StandardCharsets.UTF_8);
... process the lines
Files.write(fpath, lines, StandardCharsets.UTF_8);

Editing a text file in java

I want add few strings to a text file in a particular location.
I have used BufferedReader to read the text file. Then I added the string at the particular position and wrote the modified text to a new temp file using BufferedWriter.
Then I deleted the old file and renamed the temp file to old file name.
This works sometimes and does not work sometimes. The delete() function sometimes does not delete the file. I have closed all the BufferedWriter's, but the problem still occurs sometimes.
Code:
public boolean cart(String uname, String item) throws IOException {
File file = new File("C:\\$$$$.tmp");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
File fileop = new File("C:\\value.text");
FileReader fr = new FileReader(fileop.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null) {
String val[] = line.split(",");
if (val[0].equals(uname)) {
String linenew = line + item + "&";
bw.append(linenew);
bw.newLine();
bw.flush();
} else {
bw.append(line);
bw.newLine();
bw.flush();
}
}
br.close();
bw.close();
fileop.delete();
file.renameTo(fileop);
return true;
}
I found the answer by myself after spending one full day of searching..
Answer is:
It is enough to close the bufferedReader but also the fileReader..
fr.close(); should be inserted after br.close();

Modifying a file at a specific line in Java

I'm writing a method that will allow me to input a line at a specific point in a file, such as a .txt or .vbs script. The problem I'm having is the writing back part, the output file is blank- not containing the entries of my ArrayList scriptCollection. Here is my test method code;
public void testMethod()throws Exception
{
BufferedReader br = new BufferedReader(new FileReader("C:/Users/jchild/Desktop/PrintScript.vbs"));
int indexNo = 1;
int appendAt=0;
String line;
while((line = br.readLine()) != null)
{
scriptCollection.add(line);
if(line.contains("Add at this point"))
{
System.out.println("Successfully read and compared"); //this is just for test output
appendAt = appendAt + indexNo;
}
indexNo++;
}
br.close();
scriptCollection.add(appendAt++,"Appended here");
System.out.println(scriptCollection.toString()); //this is just for test output
//here's what's causing the problem
FileOutputStream fos = new FileOutputStream("C:/Users/jchild/Desktop/PrintScript.txt");
PrintWriter is = new PrintWriter(fos);
for(String temp : scriptCollection)
{
is.println(temp);
}
scriptCollection.clear();
}
You have to close the streams.

Writing multiple queries from a test file

public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.

Categories

Resources