This one's a fun one. I'd appreciate any bit of help, and no previous stackoverflow questions are pointing me in the right location. Docs also weren't very helpful to me.
I'm being thrown a FileNotFoundException with this block of code:
public static int wordOccurance(Word t, File D) throws FileNotFoundException
{
int occurance = 0;
BufferedReader mainReader = new BufferedReader(new FileReader(D));
Scanner kb = new Scanner(mainReader);
My tester file does not cause this to occur: ie. "File tester = new File("C:\read.txt");"
But the problem occurs solely when I pass a File constructed by this method:
public static File makeAndCombineFile(String FileOne, String FileTwo) throws IOException
{
BufferedReader mainReader = null;// null holder value for the later useful bufferedReader
Scanner kb = null;// null holder for later useful Scanner
StringBuilder sb = new StringBuilder();
OTHER CONDITIONS BETWEEN THESE TWO CHUNKS. MOST LIKELY NOT PERTINENT. ALSO RETURN FILE, JUST IF ONE INPUT IS NULL.
else //in case both are good to go and obviously not null
{
mainReader = new BufferedReader(new FileReader(FileOne));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine() + "\n");
mainReader = new BufferedReader(new FileReader(FileTwo));
kb = new Scanner(mainReader);
while(kb.hasNext())
sb.append(kb.nextLine()+ "\n");
kb.close();
return new File(sb.toString());
}
}
It took me a while to figure out what was going on here, but it looks to me like you think that this line:
return new File(sb.toString());
creates a file on disk containing the text read from the two scanners. It does not. It creates a java.io.File, which is basically a representation of a file path; the path represented by this File is the data read from the scanners. In other words, if FileOne and FileTwo contained the text to War and Peace, then the path represented by that file would be the the text of War and Peace. The file will not have been created on disk; no data will have been written to it. You've just created an object that refers to a file that does not exist.
Use a FileWriter, perhaps in conjunction with a PrintWriter, to save the lines of text into a file; then you can create a File object containing the name of that file and pass it to your other routine:
PrintWriter pw = new PrintWriter(new FileWriter("somename.txt"));
while(kb.hasNext())
pw.println(kb.nextLine());
pw.close();
return new File("somename.txt");
Related
I want to append to the file and if its not empty; and want to write if its empty. Below is is my code. write function works, append is not. Can anyone guide here?
public class Filecreate {
public static void main(String args[]) throws IOException {
File file = new File("newFileCreated.txt");
System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
FileWriter myWriter = new FileWriter(file);
if((int)file.length() != 0){
myWriter.append("appended text\n");
}else{
myWriter.write("Files in Java might be tricky, but it is fun enough!");
}
myWriter.close();
System.out.println("file length after writing to file "+file.length());
}
}
You don't need to worry about whether or not the file contains anything. Just apply the argument of true to the append parameter in the FileWriter constructor then always use the Writer#append() method, for example:
String ls = System.lineSeparator();
String file = "MyFile.txt";
FileWriter myWriter = new FileWriter(file, true)
myWriter.append("appended text" + ls);
/* Immediately write the stream to file. Only really
required if the writes are in a loop of some kind
and you want to see the write results right away.
The close() method also flushes the stream to file
before the close takes place. */
myWriter.flush();
System.out.println("File length after writing to file " +
new File(file).length());
myWriter .close();
If the file doesn't already exist it will be automatically created
and the line appended to it.
If the file is created but is empty then the line is appended to it.
If the file does contain content then the line is merely appended to
that content.
The issue occurs because you measure file's size after you open it. Thus, you have to check file's size before you open it. Also, I won't recommend to cast long to int, because your solution won't work on big files. To conclude, following code will work for you:
public static void main(String[] args) throws IOException {
File file = new File("newFileCreated.txt");
long fileSize = file.length();
System.out.println("file path "+file.getAbsolutePath() +" file length - "+file.length());
FileWriter myWriter = new FileWriter(file);
if(fileSize > 0L){
myWriter.append("appended text\n");
}else{
myWriter.write("Files in Java might be tricky, but it is fun enough!");
}
myWriter.close();
System.out.println("file length after writing to file "+file.length());
}
I have the below java code in which i am passing a file name to the the calling method lets say below code is initially the code is
File file = new File("C:\\oabc.csv");
String filename = file.getName();
s = getFileExtension(file) ;
if (s.equalsIgnoreCase(".csv"))
{
convertcsvtoexcel(filename);
}
now since there is an csv file that is being passed so it will call the method to convert the csv to excel till that stage i have tried to debug i am getting the filename but below is the convert code that is called in which it not find the filename throwing an exception that file not found exception
public static void convertcsvtoexcel(String filename) throws Exception {
ArrayList arList=null;
ArrayList al=null;
String thisLine;
int count=0;
FileInputStream file1 = null ;
file1 = new FileInputStream(new File(filename));
DataInputStream myInput = new DataInputStream(file1);
int i=0;
But it in the above code it throws the error at line file1 = new FileInputStream(new File(filename)); saying that it does not found file abc.csv at the specified location
getName() returns the file name without any directory information, so in
String name=file.getName();
File file2=new File(name);
file2 and file are not pointing to the same file, unless file is in the current directory.
In your code, pass a File object to your method to avoid path conversion issues.
You should use convertcsvtoexcel(getPath()).
in the following line of code you are just passing the file name.To make it work pass the entire file path + file name.
file1 = new FileInputStream(new File(filename));
file1 = new FileInputStream(new File("C:\\oabc.csv")); this should work.
Hello I am making a addon for bukkit a minecraft server modding program. This program requires me to put a jar into a foulder with an addon text document to provide class locations anyway. Then it uses my class and cast it into the class into the a class that it requires my class to inherit from. I am trying to write a text file in the same directory as my program so i wrote this(it is for a money program) (playerName is a pramater i used it as the filename because it is the player you are keeping balance for)
try{
FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");
writer = new BufferedWriter(fstream);
writer.write("30");
return 30;
}
catch(Exception err){
getLogger().log(Level.INFO, "Exception occoured!{0}", err.getMessage());
return -1;
}
when i try to read it with this code it throws an exception
BufferedReader reader = new BufferedReader(new FileReader(new File(".").getAbsolutePath()+"/"+playerName));
Integer i = Integer.getInteger(reader.readLine());
return i.intValue();
Also i cannot find the text document it suposedly wrote. Any advice?
Also i would like to try to save it back a file so it is not saved in the .jar file but i dont know how to do that.
Also is there a possibility it is saving the file in the folder that the program that is using the class? Thanks XD
That’s the strangest thing I’ve seen for long:
FileWriter fstream = new FileWriter(new File(".").getAbsolutePath()+File.separator+playerName + ".txt",true);
getLogger().log(Level.INFO,"trying to save text document to " + new File("").getAbsolutePath()+File.separator+playerName + ".tct");
Try to clean up:
File f=new File(playerName + ".txt");
FileWriter fstream = new FileWriter(f, true);
getLogger().log(Level.INFO,"trying to save text document to " + f.getAbsolutePath());
Next thing: you should always close files after working with then.
Then your file names do not match. One time it is playername+".txt" the next time it is just playername
But the biggest mistake:
Integer i = Integer.getInteger(reader.readLine());
return i.intValue();
Integer.getInteger does not parse the string. It will look for a system property of that name (you won’t have a system property named "30") and interpret this as integer if it exists. In your case it will return null thus you get a NullPointerException when calling intValue on it. Use Integer.parseInt instead:
try(BufferedReader reader = new BufferedReader(new FileReader(playerName+".txt"))) {
Integer i = Integer.parseInt(reader.readLine());
return i.intValue();
}
Java newbie here!
I'm writing a program to practice reading input and writing output to files. I've finished coding the program, but when I run it, the program just catches and proceeds with a FileNotFoundException.
The file is in the source folder for the program, and I've even tried placing it in every folder related to the program. I've tried:
Declaring the exceptions in the method header
Surrounding the section-in-question with a try/catch block.
Both of the above together.
Here's the relevant code that is causing problems. Is there something that sticks out that I'm missing?
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
String playerHighestScore = "", playerLowestScore = "";
int numPlayers = 0, scoreHighest = 0, scoreLowest = 0;
System.out.println("Enter an input file name: ");
String inputFileName = keyboard.nextLine();
String outputFileName = getOutputFileName(keyboard, inputFileName);
File inputFile = new File(inputFileName);
try {
Scanner reader = new Scanner(inputFile);
reader.close();
}
catch (FileNotFoundException exception) {
System.out.println("There was a problem reading from the file.");
System.exit(0);
}
Scanner reader = new Scanner(inputFile);
PrintWriter writer = new PrintWriter(outputFileName);
The answer is simple. If you get a FilENotFoundException, obviously the reason is File Not Found in the given path.
If you use an IDE, path for the working directory is different from the source directory.
For example, if you are using NetBeans, your source files are inside /src. But your working directory (.) is the project directory.
In the other hand, the problem may be the thing that #Don mentioned. If you are going for a cross platform approach, you can use "/" in paths. It works irrespective to the OS.
Example : String fileName = "C:/Directory/File.txt";
And these paths are case sensitive. So make sure you use the correct case. (It won't be a problem in Windows, until you package the program.)
So I'm trying to read a file using the Scanner, however, all the contents of the file are wiped, and then it reads nothing. Here are the methods I've ran in succession, in my Main method:
private static Scanner x;
private static Formatter y;
public void openMainFile(String name){
try{
x = new Scanner(new File("main.mcmm");
y = new Formatter("main.mcmm");
}catch(Exception e){
GUI.error(2);
}
}
This method runs perfectly fine
public void readModMainFile(){
while(x.hasNext()){
Main.name = x.next();
Main.ver = x.nextFloat();
Main.base = x.nextBoolean();
Main.dev = x.next();
Main.date = x.next();
}
}
After this method runs, the file is empty, and the 'Main.-' variables don't have any values.
Don't open the same file for reading and writing at the same time. Write into a temporary file first, then rename it. Alternatively, you can read the whole file first, store everything, close the Scanner and then you can overwrite the file.
Your Formatter is truncating the output file every time. From your comments in this post, you indicate that the number of variables will remain constant. You could use a temporary file to achieve this (+1 to #biziclop):
File inputFile = new File("main.mcmm");
Scanner scanner = new Scanner(inputFile);
File tempFile = File.createTempFile("main.mcmm",".temp");
Formatter y = new Formatter(tempFile);
y.format("%s", name);
// more reading & formatting, etc.
y.close();
scanner.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Remember to close both the Scanner and Formatter so that the input & output files can be deleted & renamed respectively.