Not creating file (Java) - java

For some reason I keep on getting the following error when I compile my code. I have the correct preprocessor directives (import statements), and no syntax errors but whenever I compile my code I am given

probably,your dateFile is empty which might be the reason for this exception
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt()
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
refer http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = new File("test.txt");
FileWriter fw = new FileWriter(dateFile);
BufferedWriter bw = new BufferedWriter(fw);
Scanner reader = new Scanner(dateFile);
try
{
// if file doesnt exists, then create it
if (!dateFile.exists())
{
dateFile.createNewFile();
bw.write("1");
bw.close();
System.out.println("Done");
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
bw.write(""+duration);
bw.flush();
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File(""+fileName+".txt");
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
fw = new FileWriter(newSession.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Now it should work.
I add this two lines:
bw.write(""+duration);
bw.flush();
you were never write in the File.
Remember to .flush() your buffer.. if you want it to write on the file before you close it!
notice that i changed the path of the file to let it work on my pc so change it again

Related

User input into a text file in java

I want a user to be able to copy and paste multi-line text into the console and then save it to a specific text file ("weather.text" in this case which is located in a data folder within the same package). I've been working on this simple task for a few hours and the solution is evading me. I'm new to java so I apologize in advance.
This static function is called from the main launcher class.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Scanner;
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
str = br.readLine();
//save the user input data to text file
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
writer.print(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
currently I'm experiencing 2 problems.
1) The code above seems to only save the first line pasted into the console into the console.
2) The text file being saved is in the global project folder and not the specified data sub folder.
Any help or suggestions are appreciated. Thank you.
You are writing str, but str is just the first line in br You have to read all lines in a loop.
Try this code:
public static void writeFile()
{
//set up for the user input
Reader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
String str = null;
try {
//prompt the user to input data
System.out.println("Type or paste your data and hit Ctrl + z");
PrintWriter writer = new PrintWriter("weather.txt", "UTF-8");
while((str = br.readLine())!=null)
{
//save the line
writer.println(str);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
about the second issue, the file is written in the working directory of your application.

Simple file read write code won't work

I have created a simple file read and write program. When compiling, the program shows no errors and runs without problem, but when I try to open the output file, I get a "file corrupted" error, and the size of the file is 0kb.
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class Extention
{
FileInputStream filein;
FileOutputStream fileout;
void asdf() throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
System.out.print("/**");
System.out.print("\n");
System.out.print("* Created by Arul on 6/15/2016 *");
System.out.print("\n");
System.out.print("**/");
System.out.print("\n");
try {
System.out.print("Enter Name of the file to read : ");
filein = new FileInputStream(br.readLine());
System.out.print("Enter Name of the file to write : ");
fileout = new FileOutputStream(br.readLine());
int i;
do {
i = filein.read();
if (i == -1)
break;
fileout.write(i);
} while (i != -1);
} catch (FileNotFoundException f) {
System.out.println("Exception : File not found!");
} finally {
filein.close();
fileout.close();
}
}
public static void main(String arg[]) throws IOException
{
Extention d = new Extention();
d.asdf();
}
}
When you say, "File corrupted", is this a Java error which you get during execution of your program, or is this an error when you double click on the created file?
If it's the latter, it all depends on what you are trying to copy. If you used it to copy an TXT file, but you changed the file ending to MP3, you would find that, when you double click on the file, your media player will be selected to open the text file and won't understand the text data.

File doesn't exist but says it does?

Alot of people have the problem "Says File doesn't exist, but it does" but my problem is the opposite, the file doesn't exist but it says it does.
Unsure on how to solve this problem and other topics just come up with "File doesn't exist but it does", etc.
Here's my code:
package New;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
public class FileEditor {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
System.out.println("Where is the file stored ex: C:/Users/Name/Place/filename.txt");
String a = scan.nextLine();
File file = new File(a);
FileWriter writer = new FileWriter(file);
BufferedWriter bwriter = new BufferedWriter(writer);
if(!file.exists()){
System.out.println("File does not exist.");
}
else{
System.out.println("Start editing? y/n");
String b = scan.nextLine();
Don't create the FileWriter/BufferedWriter until AFTER you verify the file exists.
The file does exist. You're creating it right before you check whether it exists:
FileWriter writer = new FileWriter(file);

Writing Output to a text file

So I'm trying to create a program that takes input in the form of a First and Last Name and then printing it to a Output.txt file.
I'm sort of new to programming, and I think I'm derping on this.
I just keep getting an error on the last part of my program.
PrintInitials.java:21: error: <identifier> expected
} output.close();
^
1 error
Here's my Code
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} output.close();
}
do it like this:
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your first and last name separated by a space: ");
String first = stdIn.next(); // first name
String last = stdIn.next(); // last name
stdIn.close();
try (FileWriter writer = new FileWriter(new File("Output.txt"), true); // autocloseable
PrintWriter output = new PrintWriter(writer)) { // autocloseable
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} catch (IOException e) {
e.printStackTrace();
}
The Writers will be closed automatically.
The problem is that before closing the stream, you are closing the method body. so the 'output.close();' is outside the method and into the class body.
Your new code should look like this:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials{
public static void main(String[] args){
try{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
If you havent already, have a look into Java Basic Syntax
and the docs of PrintWriter to check what exceptions are thrown by what method so you can either catch them and handle them like i did above, or just pass them on.
Also, using an IDE such as eclipse, will show you all syntax errors real-time as you code so you dont have to compile every time yourself to check if your syntax is correct. Also most IDE's often come with sugested solutions for perticular errors. Other than this, it will warn you about what method throws what exception so you can catch them.
try this
BufferedWriter br= new BufferedWriter(new FileWriter(file)){
br.write(first + " " + last);
}

Java - How to remove blank lines from a text file

I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good

Categories