Basically, I'm trying to create a simple database app with automatically generated IDs in each student entry. The program reads the previous highest ID and adds 1 to it to create the next one.
However, even though the text document has numbers in it, BufferedReader keeps returning null when using readLine
I checked if my int parsing was the issue, but i realized it was the bufferedreader by saving the readline to a variable then printing it, where I got the result of null. I also tried using scanner file reading which didn't work, and I checked all related classes and methods to try to figure it out.
This code creates the topsid file and writes 0 to initialize it, which is being read as null
if(MiscProcesses.firstStartup() == false) //method that checks if these files exist
{
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
fw.write("0");
fw.close();
}
This code is responsible for reading the file and hence finding a higher id value
Student (String[] studata)
{
//checking highest SID
File topsid = new File("topsid.txt");
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
//checking high sid file and getting new sid
String test = br.readLine();
System.out.println(test+" <test"); <this ends up printing null
int sid;
sid = Integer.parseInt(test)+1;
System.out.println(sid);
fw.write(Integer.toString(sid));
this.id = sid;
...
br.close();
fr.close();
fw.close();
}
When I open the topsid file before the second code runs, it's all fine and the file contains a zero.
I would expect the bufferedreader to read "0" but it just reads null, and when I open the file after the code runs, the data inside gets erased.
FileWriter fw = new FileWriter(topsid);
FileReader fr = new FileReader(topsid);
BufferedReader br = new BufferedReader(fr);
Creating the FileWriter like this will stomp the existing file before you read its contents.
If you want to read something from the file, then write something back after, create the FileWriter after you have read from it.
Related
I want to edit certain values(a row values) of a csv file based on a specific value of that row (an id). I am able to read and write (append) the values in it but cannot figure out how to edit and delete them.
Here is a small fragment of code for what I am doing for reading the file and appending values:
FileWriter writer = new FileWriter("file.csv", true);
try {
FileInputStream fstream = new FileInputStream("file.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] fields = strLine.split(",");
if (fields[1].equals("value") {
fields[1] = "different value";
}
writer.append(fields);
}
catch(...)
}
But I can't work out how to write the values back into the same spot in the file.
Unfortunately you can't open a single file for both reading and writing at the same time. You need to read the file and close it before opening it for writing.
The potential solutions are:
Write the output to a different file and then replace the original when complete
Keep all the output in internal variables then, once you've finished reading, close the file and reopen it for writing.
I need to read contents of a file as a server, and then send the read data file, for the client so the client print it out on the Client terminal.
The problem is that I can't find a way or method to read a txt file from the current directory which my java file and txt file are existed.
Please help me.
There are many ways to read text file or file in java. It depend on you to that in which format you need to pass your file content to client side.
Here are some method to reading file in java.
1. Using BufferedReader class
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
String curLine = line;
//Process line
}
2.Using Apache Common IOUtils with the class IOUtils.toString() method.
FileInputStream inputStream = new FileInputStream("FILEPATH/FILENAME");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
3.Using the Scanner class in Java and the FileReader
Scanner in = new Scanner(new FileReader("FILENAME/FILEPATH"));
while (scanner.hasNextLine()){
//process each line in some way
String line = scanner.nextLine();
}
Scanner has several methods for reading in strings, numbers, etc...
4.In JAVA 7 this is the best way to simply read a textfile
new String(Files.readAllBytes(...))
or Files.readAllLines(...)
Path path = Paths.get("FILENAME");
List<String> allLines = Files.readAllLines(path, ENCODING);
Please refer this link for more onfomation.
You can use BufferedReader to read from a txt file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
here fileName is a string that contain your absolute file name.
eg : fileName = "C:\temp\test.txt";
You can read file by using BufferedReader.
File file=new File("filepath");
BufferedReader br=new BufferedReader(new FileReader(file)); //Here you create an object of bufferedreader which file read through filereader
String data=br.readLine();
while(data!=null)
{
System.out.println(data); // Writing in the console
data=br.readLine();
}
This will taking input from file and giving output to console.If you want it write in other file then use BufferedWriter.
File out=new File("outputfilepath");
BufferedWriter bw=new BufferedWriter(new FileWriter(out));
simply us bw.write() instead of System.out.println();.
I know this is very basic stuff but for some reason I'm having problems with a bufferedReader/ Writer. I am trying to get the first line of text and return it to another method. However, for some reason the writer doesn't seem to be writing to the temp file and it isn't changing the name of the temp file either.
By throwing a few print statements I have been able to figure out:
The while loop is operating correctly
The if else statement is operating correctly
The tempFile is not writing to a text file correctly
The tempFile is not renaming correctly
There are no errors being thrown
private static String wavFinder() throws IOException{
String currentWav=null;
int x = 1;
File inputFile = new File("C:\\convoLists/unTranscribed.txt");
File tempFile = new File("C:\\convoLists/unTranscribedtemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine = null;
while((currentLine = reader.readLine()) != null) {
if(x == 1){
currentWav = currentLine;
}
else{
writer.write(currentLine);
}
x = 2;
}
boolean successful = tempFile.renameTo(inputFile);
System.out.println("Success: " + successful);
System.out.println("currentWav = " + currentWav);
return currentWav;
}
Here is the method I am using. If you notice anything please let me know and if you have any questions I will be sure to answer them quickly. Thank you :)
First flush the steam(writer) and close them.
You can not have two files with same name. You are trying to rename the temp file with input file. You need to delete input file and then rename it to that.
reader.close();
writer.flush();
writer.close();
inputFile.delete();
Add these lines before rename and it will work
Close your buffers before trying to call renameTo.
reader.close()
writer.close()
File inputFile = new File("C:\convoLists/unTranscribed.txt");
File tempFile = new File("C:\convoLists/unTranscribedtemp.txt");
Why you have different signs for path?
Always should be //.
I've been working on a small project in Java. The program writes to a log file from different methods . But each time a method is used , the content of the file gets deleted and all what's written in it is the result of the last method.
here's a code snippet of the program :
// dir , log_file , exp_date and amount are declared in the code removed
public static void WriteHeader() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
Console console = System.console();
exp_date = console.readLine("Enter a string here: ");
bufferedWriter.write(exp_date);
bufferedWriter.close();
}
public static void WriteNewLine() throws IOException
{
FileWriter fileWriter = new FileWriter(dir+"/"+log_file);
BufferedWriter bufferedWriter2 = new BufferedWriter(fileWriter);
Console console = System.console();
amount = console.readLine("Enter another string here :");
bufferedWriter2.newLine();
bufferedWriter2.write(amount);
bufferedWriter2.close();
}
You need to create the writer in append mode http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
You need to open file in append mode otherwise once you close the file and reopen it to write, it would erase previous data. http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String, boolean)
FileWriter fileWriter = new FileWriter(dir+"/"+log_file, true);
FileWriter fw = new FileWriter(file, true);
I am pretty sure FileWriter has an overloaded constructor for appending to a file instead of overwriting a file
I would also check if the file exists first.
file.exists();
I'm developing a app which opens a file and writes its content in another existing file with adifferent name.
The problem is that some chars, which don't exist in ASCII(I think), for example (char)144 or (char)154, are replaced by (char)63 or the *** question mark ->?.
I have tried to change VM charset but the problem is not solved.
Here the part of the code we are interested in:
File out = new File("new_clientK.swf");
BufferedReader reader = new BufferedReader(new FileReader(new File("input.swf")));
PrintWriter writer = new PrintWriter(new FileWriter(out));
String line = null;
//The first line is edited
line = reader.readLine();
writer.append(line.replace(oldstring, newstring));
writer.append((char) 10);
//The first line is added, now, I get all the remaining code and add it
//char by char
int charnum = 0;
while ((charnum = reader.read()) != -1) {
writer.append((char) (charnum));
}
reader.close();
writer.close();
So you should not use a text oriented API like BufferedReader/PrintWriter but some raw binary API like FileInputStream/FileOutputStream.
Because you can't even play with encoding, a SWF file is not a document and contains raw binary data.