Printing to .txt file in java not working - java

I am wanting to store some variables in a .txt file for storage and have attempted to use the PrintWriter functions, however the txt file i am trying to create doesn't actually create, let alone write to the file!
Code:
if(new String("SimpleBLEBroadcaster").equals(result.getDevice().getName()))
peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() +" Packet length: " + PacketLength + " Packet Data: " + "0x" + R + "\n");
File myObj = new File("C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt");
PrintWriter DataOut = null;
try {
DataOut = new PrintWriter("Data.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataOut.println(R);
DataOut.close();
I have followed a few tutorials on how best to use the print writer function and copied a youtube tutorial but using my variables and i cant understand why the txt file isnt being created. i even tried generating the file prior to writing to it. Any help would be much appreciated.

Your constructor for PrintWriter should be as follows;
DataOut = new PrintWriter(myObj);
Refer: PrintWriter
----------------Explanation-----------------
What your code is doing is that the PrintWriter is not referring to the same file that you are instantiating in the code above.
File myObj = new File("C:\Users\Josh Gascoigne\Documents\Uni stuff\Android Studio\Data.txt");
What you code is possibly doing is creating a new file Data.txt in the working directory of the program.
So basically, you referring to the file C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt is redundant.
Referring to the variable myObj in the PrintWriter constructor should fix that redundancy. (Provided that is what your use case is.)

There's no such path as c:\ on any Android device.
Then your print writer too.
You didn't even specify any path.
At least try something like
File destination = new File(getExternalFilesDir(null), "data.txt");
Dataout = new PrintWriter(destination);
Dataout.println(R);
Dataout.close();

Related

Java: Bank simulation: Write to file, erased text/writing symbols

As a way to learn java, I attempted to write something simulating a bank(adding or removing numbers). I succeeded in creating a file(if one does not exist already), and then read from it, but when I attempt to write to it, it fails. I started with FileWriter, where it just erased the text in the document(balance.txt). I then tried BufferedWriter, and it wrote to the document, but it was just symbols instead of actual text/numbers. I'm aware that I'm a newbie when it comes to coding, but is there a solution to this? Thank you.
if (choice.equals("ADD")){
System.out.println("Currently selected: " + choice);
//write to file
try {
String filePath = "C:\\Users\\user\\Desktop\\programming\\projects\\java\\RandomStuff\\Bank\\balance.txt";
// System.out.println("How much would you like to add?");
// Scanner inputAdd = new Scanner(System.in);
// String balanceToAdd = inputAdd.nextLine();
// writeToFile.write(balanceToAdd);
int balanceToAdd = 1;
BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
out.write(balanceToAdd);
out.close();
System.out.println("Added: " + balanceToAdd);
} //try end
catch(IOException e){
System.out.println("Error(line56): " + e.getMessage());
}
public FileWriter(String fileName,
boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));

JAVA - File I/O cant get file to read

I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = new Scanner("inventory.csv");
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// ...
return size;
}
Here is the output I'm getting with no syntax errors.
Unable to open file inventory.csv.
considering it's in the same folder.
Same folder as what? inventory.csv was not present in the current working directory when you executed your program.
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.
In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here
You should try this
try{
FileReader fr=new FileReader(filename);
BufferedReader br =new BufferedReader(fr)
String lime=br.readLine();
br.close();
catch(Exeption e){}

PrintWriter not writing to text file

I'm trying to create a save feature which outputs stored data to a text file. I've tried using a Printwriter to write to the file and although I'm not getting any errors and the output seems to be correct, the text file remains blank. Here is my code:
public void saveConfiguration() throws IOException{
PrintWriter pw = new PrintWriter("locos.txt");
for (int i = 0; i < currentTrains.size(); i++) {
//confirm data is correct
System.out.println(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
//write to file
pw.write(currentTrains.get(i).getAddress() + " " +
currentTrains.get(i).getName() + " " + "\n");
}
pw.close();
//for testing
System.out.println("File Saved");
}
Here's what's on the console:
8 class 08
55 Jinty
44 BR44
File Saved
The above data that gets printed out is correct, but it's not getting written to the file. Can anyone explain how to do this properly?
Edit: I don't know if this is relevant, but I'm running this on a Tomcat server.
You should try handling the PrintWriter and a Filerwriter instead...
Example:
PrintWriter pw = new PrintWriter(new FileWriter("locos.txt"));

Java.io.FileNotFoundException using File object

File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);
while(inputFile.hasNext())
{
sum = inputFile.nextDouble() + sum;
count++;
}
inputFile.close();//close the input file
I'm trying to read data out of the text file Numbers.txt and the following code compiles fine but I get the Java.io.FileNotFoundException error when the program runs. I've also tried entering the full file path but I might have done it wrong. Any ideas?
Make Sure your text file is in the folder with your java file
because you used the direct path .
and try this code check, if still not working .
BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();
while(line !=null)
{
System.out.println(line);
line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}
Try adding
System.out.println("Full path is " + read.getCanonicalPath()
+ ", canRead=" + read.canRead()
+ ", exists=" + read.exists());
and then see whether the full path exists on your file system, and whether it is readable according to canRead.
If the file is a symlink, canRead might return true in that the symlink is resolvable even though the file to which the link points is unreadable. To deal properly with symlinks you really need to use the new java.nio.file APIs.

PrintWriter eclipse

I'm using Eclipse to write code that needs to write to an output file. the file name comes from a command-line argument. I don't know where it is creating the file. It says that my workspace is the default for the output file but it is no where to be found. This is my code
try{
PrintWriter output = new PrintWriter(new File(args[3]));
//System.out.print(args[3]);
output.append('l');
output.close();
} catch(IOException e) {
System.exit(0);
}
Add the following to your program to see the absolute path of the file.
File file = new File(args[3]);
System.err.println( "File: " + file.getAbsolutePath() );

Categories

Resources