Reading the contents of a text file [duplicate] - java

This question already has answers here:
Read text file in google GWT?
(2 answers)
Closed 7 years ago.
I'm writing an application for displaying chrats. I'm using GWT Highcharts (by Moxie Group) to display the results. I add a random number to the chart and it works without a problem.
But I want to load numbers from a text file. I just want to read the contents of a file and put it on the array or something similar. How can I do this in Java?

You can use a small program as like the below to achieve that:
You may have to change the logic to read elements the way you want it for your GWT highcharts!
public class ReadATextFile {
public static void main(String[] args) {
try (RandomAccessFile readFile = new RandomAccessFile("C:\\Test.txt", "r");) {
int EOF = (int) readFile.length();
System.out.println("Length of the file is (" + EOF + ") bytes");
//Considering to read the first 150 bytes out of 168 bytes on the file
readFile.seek(0);
byte[] bytes = new byte[EOF];
readFile.readFully(bytes);
readFile.close();
System.out.println(new String(bytes));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Where the Test.txt file's contents is something like this:
1 2 3 4
5 6 7 8
9 10 11

Related

NullPointerException when trying to read file, same exact code worked before [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last month.
I wanted to run a Java program I wrote two years ago. It needs two files as command line parameters and reads them. This program has worked great before and as it was a school project it went through many tests to make sure everything was working correctly. I downloaded the project from my submission to make sure I had the same version. Only thing this version lacked was the files to read because we were asked not to include them and rather use a path so they don't accidentally get tracked by version control. I added the files to the same directory as the main java file. When I run the program I get:
Welcome to "Name of school project"
Exception in thread "main" java.lang.NullPointerException
at practice.collection.Collection.download(Collection.java:100)
at practice.UI.UI.mainLoop(UI.java:63)
at mainFile.main(mainFile.java:60)
This is what download method in Collection looks like:
public void download(String fileName) {
Scanner fileReader = null;
try {
File file = new File(fileName);
fileReader = new Scanner(file);
while (fileReader.hasNextLine()) {
***reads lines and does some sorting***
}
fileReader.close();
}
catch (FileNotFoundException | NumberFormatException e) {
fileReader.close(); ***this is line 100***
System.out.println("Missing file!");
System.out.println("Program terminated.");
System.exit(0);
}
}
I have also made sure the files to be downloaded are the same as before, they are not empty and are being called with correct spelling, in correct order. Like this: java mainFile first_file.txt second_file.txt. Why is the program not finding the files like before?
I did check out What is a NullPointerException, and how do I fix it? but does not answer my question. I assume I get the exception because my program can't find the file and is thus referring to a file object with null value. I am trying to figure out why the file can't be found and read. I think I should be able to fix this problem without touching the code. The program behaves the same way regardless of if the files have been included.
Suggested changes for troubleshooting the underlying problem:
public void download(String fileName) {
System.out.println("fileName=" + fileName + "...");
System.out.println("current directory=" + System.getProperty("user.dir"));
Scanner fileReader = null;
try {
File file = new File(fileName);
fileReader = new Scanner(file);
while (fileReader.hasNextLine()) {
***reads lines and does some sorting***
}
fileReader.close();
}
catch (FileNotFoundException | NumberFormatException e) {
System.out.println(e); // Better to print the entire exception
//System.out.println("Missing file!"); // Q: What about NumberFormatException?
System.out.println("Program terminated.");
System.exit(0);
}
finally {
// This assumes your app won't be using the scanner again
if (fileReader != null)
fileReader.close();
}
}

Writing to txt doc on new line Java [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 4 years ago.
public void writePlayerTurnActions(String action){
File file = new File(this.playerFileName);
try {
FileWriter writer = new FileWriter(this.playerFileName);
if(!file.exists()) {
file.createNewFile();
}
writer.write(action + "\n");
writer.close();
} catch (IOException e) {
System.out.println("Error writing to player output file");
}
}
Here is the method im using to keep updating a file depending on what occurs during the execution of the program. Im calling it by
instance.writePlayerTurnActions("1");
instance.writePlayerTurnActions("2");
instance.writePlayerTurnActions("3");
When running this code the file only contains a 3... and not 1, 2, 3 on seperate lines.
Any help appreciated as i'm so confused as to whats going wrong...
you should not create a new FileWriter instance each time you want to write something (not only because of this issue, it's also very bad performance wise). Instead, keep one globally and instead of calling writer.close() when you're done writing your current String to the file, call writer.flush().

Having problems with saving text to a file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 5 years ago.
I'm having problems with saving text to a file, I'm saving text from text fields to a file. The text fields are saving to the file fine, but when I close the program re-open it and try to save a new entry, it wipes the file and corrupts it. Help would be greatly appreciated :)
// BUTTON SAVE ------------------------------------------
if(e.getSource() == btnSave)
{
// Call the saveEntry method that will copy the current
// TextField entries from the screen to the current
// record in the array in memory.
saveEntry(currentEntry);
}
public void saveEntry(int i) //
{
PersonsInfoData[i].setPersonsInfo(txtPersonsName.getText(),txtLikes.getText(),txtDislikes.getText(), txtBdayDay.getText(), txtBdayMonth.getText());
// You may also wish to write all the records that are currently in the array
// to your data file on the hard drive (USB, SSD, or equivalent)
writeFile(dataFileName);
}
public void writeFile(String fileName)
{
try
{
PrintWriter printFile = new PrintWriter(new FileWriter("BirthdayTracker.txt"));
for(int i = 0; i < numberOfEntries; i++)
{
printFile.println(PersonsInfoData[i].getPersonsName() + "," + PersonsInfoData[i].getPersonsLikes() + "," + PersonsInfoData[i].getPersonsDislikes() + "," + PersonsInfoData[i].getBdayDay() + "," + PersonsInfoData[i].getBdayMonth() );
}
printFile.close();
}
catch (Exception e)
{
System.err.println("Error Writing File: " + e.getMessage());
}
You should create the FileWriter object in append mode like below
new FileWriter("BirthdayTracker.txt", true);

FileOutputStream switching between appending and overwriting

I have made a simple data file which contains a header of only 4 bytes. These 4 bytes define how many records are stored inside the file. Both the header and record are of pre-defined sizes and cannot vary.
EDIT: Also the record only contains 4 bytes aswell. Which define just an integer number.
The LINE_SEPERATOR = byte { '\r', '\n' }
My problem is that each time I add a new record (append) I need to overwrite the header (not appending) becouse the record count should be increased by one. However the program refuses to switch between them and it just sticks with the non append mode.
addRecord code:
public void addRecord(ISaveable record)
throws IllegalArgumentException, FileNotFoundException, IOException
{
if(record == null)
{
throw new IllegalArgumentException("The given record may not be null");
}
this.header.increaseRecordCount();
writeHeader();
FileOutputStream oStream = null;
try
{
oStream = new FileOutputStream(DEFAULT_DIR, true);
long offset = calculateOffset(this.header.getRecordCount() - 1, record.getSize());
System.out.println("writing record # " + offset);
oStream.getChannel().position(offset);
PacketOutputStream pOut = new PacketOutputStream();
record.Save(pOut);
pOut.writeBytes(END_LINE);
oStream.write(pOut.Seal());
}
catch(FileNotFoundException ex)
{
throw ex;
}
catch(IOException ex)
{
throw ex;
}
finally
{
if(oStream != null)
{
oStream.flush();
oStream.close();
}
}
}
The writeHeader code:
private void writeHeader()
throws IOException
{
FileOutputStream oStream = null;
try
{
oStream = new FileOutputStream(DEFAULT_DIR, false);
oStream.getChannel().position(0);
PacketOutputStream pOut = new PacketOutputStream();
this.header.Save(pOut);
pOut.writeBytes(END_LINE);
oStream.write(pOut.Seal());
}
catch(IOException ex)
{
throw ex;
}
finally
{
if(oStream != null)
{
oStream.flush();
oStream.close();
}
}
}
As you can see I am using the booleans in the constructor of FileOutputStream correctly. Giving the writeHeader a false (becouse I want to overwrite the existing header) and the record a true (becouse it should be added to the end of the file). Please ignore the fact that setting append to true that it will automaticly seek to the end. The calculateOffset method is for future implementations.
I have done experiments where I only write the header everytime. It works perfectly when set to not append. And as expected when it's set to append it will add multiple headers.
The result I'm getting from my file right now after trying to add 4 records is only 2 lines. The header is perfect, there's nothing wrong with it. However all 4 records are written on the next line overwriting eachother.
The resulting debug text:
writing record # 6
writing record # 12
writing record # 18
writing record # 24
reading record # 6
3457
All record positions are correct, however the '3457' is the result of all 4 records overwritten on the same line.
If you want to write to multiple points in a file, you should really consider using RandomAccessFile, which was designed for this purpose.
Update: You should also use the same RandomAccessFile instance for all writes instead of creating one separately every time you update the header or the contents.

Buffered writer writes memory trash on text file

My buffered writer is writting some randomly trash in my txt file. I use int nodes = Integer.valueOf(NODES_TEXT_FIELD.getText()); to store the value of one TextField that should only accept ints.
this is my writer:
private static void writeOnFile(BufferedWriter writer, int nodes){
try {
System.out.println(nodes);
System.out.println("Last check before write");
writer.write(nodes);
System.out.println(nodes);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Failed to write data on file");
e.printStackTrace();
}
}
My output:
2
Last check before write
2
and in the text file I found: '?' (which changes to another memory trash depending on what number you input
Anybody has any Idea of what might be wrong? I stuck here for 5 hours until now..
Because write() writes a character .
Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.
Parameters:
c - int specifying a character to be written
You can use Writer#write(String):
writer.write(String.valueOf(nodes));
Try this:
Writer wr = new FileWriter("thefileToWriteTo.txt");
wr.write( String.valueOf(nodes) );
wr.close();
you can always extract the writing into a loop if that is what you are doing with your nodes or some kind of escaping, it would be more helpful if you explain what is it that you are actually trying to achieve by writing this to a file, as we might advise you on that.

Categories

Resources