Is this correctly writing to a text file? - java

I am trying to save the integers in an array to a text file. Neither of these seem to be doing the trick while sitting in my main method and I was wondering if someone could point out my mistake.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File ("C:/Users/Usman/Desktop/directory/scores.txt");
PrintWriter writer = new PrintWriter("scores.txt");
writer.println("Player 1 score: " + scorep1[0]);
writer.println("Player 2 score: " + scorep1[1]);
writer.println("Player 3 score: " + scorep1[2]);
writer.println("Player 4 score: " + scorep1[3]);
writer.close();
System.exit(0);
}
No score.txt file is created on my desktop in either of these attempts.
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
File file = new File("C:/Users/Me/Desktop/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
System.exit(0);
}
EDIT: This is what I have made of the answers so far, please feel free to edit the wrong bit so I can clearly see what I've missed.
System.out.println("What's happening");
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
FileWriter fileWriter = new FileWriter(file);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
Also what about this:
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Rather a problem of directory
see this:
How to use PrintWriter and File classes in Java?
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
// NOK for C:/Users see below
// File file = new File("C:/Users/Me/Desktop/file.txt");
File file = new File("C:/classical_dir/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
This works well on my pc:
File file = new File("C:/foo/bar/blurps/file.txt");
This throws an exception: windows seems not to want it
File file = new File("C:/Users/Me/Desktop/file.txt");
because, C:/Users/Me seems to be prohibited: C:/Users seems to be protected by system
see this for writing in User directory: how can I create a file in the current user's home directory using Java?
String path = System.getProperty("user.home") + File.separator + "Desktop/file1.txt";
File file = new File(path);
see this also: How to get the Desktop path in java

Because File object does not create a physical copy of a file. For details follow this linkDoes creating a File object create a physical file or touch anything outside the JVM?
Now if we come to your solution then first make a empty file on the disk by following command
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to open.
String fileName = "C:\\Users\\MOSSAD\\Desktop\\new\\temp.txt";
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
File file = new File (fileName);
PrintWriter writer = new PrintWriter(file);
writer.println("Player 1 score: " + 5);
writer.println("Player 2 score: " + 2);
writer.println("Player 3 score: " + 3);
writer.println("Player 4 score: " + 4);
writer.close();
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
you need to use double slash in path .link

Related

createNewFile() Throws FileNotFoundException When Given the Correct FilePath

Here is my code below:
public void playerNaming() throws IOException {
Scanner pickName = new Scanner(System.in);
System.out.println("What do you want your username to be?");
String playerName = pickName.nextLine();
userName = playerName;
File file1 = new File("PlayerFiles\\" + playerName + ".txt");
File file2 = new File(file1.getAbsolutePath());
System.out.println(file2);
file2.createNewFile();
BufferedWriter file3 = new BufferedWriter(new FileWriter(file2));
}
On line file2.createNewFile(); It throws
java.io.FileNotFoundException: (Insert correct FilePath here) The system cannot find the path specified
What is wrong? According to all the articles and other stackoverflow questions I have read, this should work.
Check your file path :
public static void main(String args[])
{
try {
// Get the file
File f = new File("F:\\program1.txt");
// Create new file
// if it does not exist
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
Note : The file “F:\program.txt” is a existing file in F: Directory.

Open and display data from file

I have a file that contains score data for a game (the player name and their final score.
I want to open the file and have the data contained to be displayed so that it would look something like
PLAYER SCORE
------ -----
John 1000
Steve 2000
The file is definitely saving the data that I want but I cannot get it to display the data.
I have tried various things along the lines of:
public static void loadScores() {
boolean fileIsValid;
String filename = "";
File file;
do {
fileIsValid = true;
clrscr();
System.out.println("\t\t\t\t\t\t\t\t\tLEADERBOARDS");
printWave();
if (!fileIsValid) {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
System.out.println("");
filename = "scores.gz";
file = new File(filename);
if (!file.exists()) {
fileIsValid = false;
}
} while (!fileIsValid);
System.out.println(file);
pressKey();
}
This is how I would do it.
public static void loadScores() {
File file = null;
try{
file = new File("scores.gz");
if (!file.exists()) {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
} else {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Note: Your original code will sit in an infinite loop until the file is created! Also there is no sleep in your loop, thus you will query the file system continuously without a wait period.
This doesn't require 3rd party libraries but Apache commons has some nice util classes, also for reading files: http://commons.apache.org/proper/commons-io/description.html

Java PrintWriter doesn't append to existing .txt file after closing

I've run into some problems trying to append to an existing text file.
It doesn't seem to append a line text. So far i've got this method:
public static void addLine(File f, String line) {
try {
FileWriter fw = new FileWriter(f.getName(), true);
BufferedWriter buffer = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(buffer);
pw.println(line);
pw.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
and in my main i've got the following:
public static void main(String[] args) {
File f = new File("adresOfFile");
if (f.exists() && !f.isDirectory()) {
System.out.println("File " + f.getName() + " exists!");
System.out.println("\n" + "Path: " + f.getAbsolutePath());
System.out.println("\n" + "Parent: " + f.getParent());
System.out.println("\n" + "--------------CONTENT OF FILE-------------");
addLine(f, "");
addLine(f, "The line to append");
try {
displayContent(f);
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("File not found");
}
}
When I run the program it doesn't seem to give any errors. Running the program should print out the existing text (displayContent), which is done after appending (addLine). But when I run it, it only shows the existing text, without the appended line.
It doesn't show up in the text file either. I tried to put a System.out.println(); in the method, and it prints, so I know its running the method properly, just not appending.
EDIT AWNSER: replaced f.getName() with f, and added pw.flush before pw.close()
I think that your displayContent(File) function has bugs.
The above code does append to the file.
Have a look at the file to see if anything is appended.
Also do you need to create PrintWriter object each time you append a line?
If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object.

Buffered Writer overwriting file when not wanted

I have this code here that takes in 3 arguments, A Directory, a Filename, and a number. The program creates the filename in the directory and writes the number in it. So I can say...
>java D: myName.txt Clay 100
which will create a file named myName.txt in D: and says 100 in it.
If myName is taken up, it changes the name to myName(2), then myName(3) (if myName(2) taken up). The only problem is that when it changes the name to myName(2) and writes, it overwrites myName. I dont want it to overwrite myName, I want it to just create a new file with that name. Ive looked at similar questions and the common answer is the flush and close the writer which ive done And it still doesnt work.
Any help would be appreciated, here is my code so fart...
import java.io.*;
public class filetasktest{
public static void main(String[] args) throws IOException{
int i = 2;
String directory = args[0];
if (directory.substring(directory.length() - 1) != "/"){
directory += "/";
}
String contactName = args[1];
String contactNumber = args[2];
String finalDirectory = directory + contactName + ".contact";
File f = new File(finalDirectory);
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(finalDirectory), "utf-8"));
writer.write(contactNumber);
} catch (IOException ex){
System.out.println(ex.getMessage());
} finally {
try {
writer.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
You need to use append mode
new BufferedWriter(new FileWriter(yourFileName, true));
here, true means that the txt should be appended at the end of file.
Check the FileWriter javadoc for more information.
Your problem is here:
while (f.exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
f.renameTo(new File(finalDirectory));
i++;
}
The renameTo method does not change the path of a File object; it renames a file on disk. The path of f stays the same throughout the loop: it starts out as D:/myName.txt and if a file by that name exists, the file is renamed as D:/myName(1).txt. The variable f still holds the path D:/myName.txt, which no longer names a file, and the content is written to D:/myName(1).txt, overwriting the previous content.
To fix this issue change the loop to:
while (new File(finalDirectory).exists()){
finalDirectory = directory + contactName + "(" + ("" + i) + ")" + ".contact";
i++;
}
Take a look at FileInputStream(String, boolean) which will allow you to flag if the file should be appended or overwritten

File handling in java

I have the below code.
The below source code is from the file x.java. The hi.html is present in the same directory as x.java.
I get a file not found exception even though the file is present. Am I missing something ?
public void sendStaticResource() throws IOException{
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try{
File file = new File("hi.html");
boolean p = file.exists();
int i = fis.available();
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while(ch!=-1){
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}catch(Exception e){
String errorMessage = "file not found";
output.write(errorMessage.getBytes());
}finally {
if(fis != null){
fis.close();
}
}
}
The directory of the .java file is not necessarily the direction your code runs in! You can check the current working dir of your program by in example:
System.out.println( System.getProperty( "user.dir" ) );
You could use the System.getProperty( "user.dir" ) string to make your relative filename an absolute one! Just prefix it to your filename :)
Take a look at your "user.dir" property.
String curDir = System.getProperty("user.dir");
That's where the program will root its search for files that don't have a complete path.
Catch the FileNotFoundException before catching Exception so as to be sure that is the real Exception type.
Since you don't give an absolute location for a file it searches from your working directory. You can store the absolute path in a property file and use that instead or use System.getProperty("user.dir") to return the directory that you are running the Java app from.
Code to get Key-Value from Property files
private void getPropertyFileValues() {
String currentPath = System.getProperty("user.dir") + System.getProperty("file.separator") + "Loader.properties";
FileInputStream fis = null;
try {
fis = new FileInputStream(currentPath);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Properties props = new Properties();
try {
props.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
String filePath= props.getProperty("FILE_PATH");
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I guess you get a NullPointerException:
FileInputStream fis = null;
then the call:
int i = fis.available();
will result in an NullPointerException as the first non-null assignment to fis is later:
fis = new FileInputStream(file);
File Handling in Java:
Use File class for Representing and manipulating file or folder/directory.
you can use constructor :
ex. File file = new File("path/file_name.txt");
or
File file = new File("Path","file_name");
File representation example:
import java.io.File;
import java.util.Date;
import java.io.*;
import java.util.*;
public class FileRepresentation {
public static void main(String[] args) {
File f =new File("path/file_name.txt");
if(f.exists()){
System.out.println("Name " + f.getName());
System.out.println("Absolute path: " +f.getAbsolutePath());
System.out.println("Is writable " +f.canWrite());
System.out.println("Is readable " + f.canRead());
System.out.println("Is File " + f.isFile());
System.out.println("Is Directory " + f.isDirectory());
System.out.println("Last Modified at " + new Date(f.lastModified()));
System.out.println("Length " + f.length() +"bytes long.");
}//if
}//main
}//class
Write data character by character, into Text file by Java:
use FileWriter Class-
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.Writer;
public class WriteFile {
public static void main(String[] args) throws Exception{
//File writer takes chars and convert into bytes and write to a file
FileWriter writer = new FileWriter("path/file_name.txt");
//if file not exits then created it, else override data
writer.write('A');
writer.write('E');
writer.write('I');
writer.write('O');
writer.write('U');
writer.close();
System.out.println("Successfully Written");
}
}

Categories

Resources