So I have a background in c++ and I am trying to learn java. Everything is pretty similar. I am having a problem thought with file i/o. So I am messing around and doing really simple programs to get the basic ideas. Here is my code to write data to a file. My code makes a file, but when I open the file it is empty and does not contain the string I told it to write.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO
{
public static void main(String[] args) throws IOException
{
//Declaring a printWriter object
PrintWriter out = new PrintWriter("myFile.txt");
out.println("hello");
}
}
The output is buffered and needs to be flush()ed to be written to a file.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
PrintWriter out = new PrintWriter("myFile.txt");
out.println("hello");
out.flush();
}
}
But you don't need to flush explicitly because that will happen anyway when you close() the writer, which you ought to be doing.
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
PrintWriter out = new PrintWriter("myFile.txt");
try {
out.println("hello");
} finally {
out.close();
}
}
}
But you also don't need to close explicitly because PrintWriter implements AutoCloseable, so you can use Java 7's automatic resource management:
package practice.with.arrays.and.io;
import java.io.IOException;
import java.io.PrintWriter;
public class PracticeWithArraysAndIO {
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter("myFile.txt")) {
out.println("hello");
}
}
}
Related
I'm trying to read a plain text file but somehow FileReader is not finding my text file. I checked the directory using getAbsolutefile() and /Users/djhanz/IdeaProjects/datalab2/pg174.txt is the exact location of the file. I tried datlab2/pg174.txt and everything I possibly could.
Here is my code
public class Program1 {
public static void main(String[] args) {
System.out.println(new File("pg174.txt").getAbsoluteFile());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/Users/djhanz/IdeaProjects/datalab2/pg174.txt")));
while (testScanner.hasNextLine())
{
System.out.println(testScanner.nextLine());
}
}
}
The text file is under the same project directory called datalab.
Can someone please enlighten me?
Use Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
FileReader("/pg174.txt") instead of FileReader("pg174.txt").
package com.example.demo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
public static void main(String[] args) throws FileNotFoundException {
System.out.println(new File("pg174.txt").getPath());
System.out.println(new File("pg174.txt").getAbsoluteFile());
System.out.println(new File("pg174.txt").getAbsolutePath());
Scanner testScanner = new Scanner(new BufferedReader(new FileReader("/pg174.txt")));
while (testScanner.hasNextLine()) {
System.out.println(testScanner.nextLine());
}
}
}
Output:
If a user don't have any web browser, which java code he should write (and which classes he needs) to download and read file? Lets say that this is the URL where the file will be downloaded:
http://www.thewebsource.serv/dir1/myfile.txt
So far I have tried to access a url, but in order to download a file what procedure I should follow.
package filedownload;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class FileDownload {
public static void main(String[] args) throws URISyntaxException, IOException {
Desktop d=Desktop.getDesktop();
d.browse(new URI("http://www.thewebsource.serv/dir1/myfile.txt"));
}
}
You could use something like this using the URL class:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
From java doc tutorials: Link
I'm trying to show a file open dialog and then create a scanner to read the selected file. When I run my code it throws a FileNotFoundException which doesn't make sense to me since it throws the exception before it opens the file selector window.
package files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main (String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI () {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
System.out.println(file.exists());
Scanner fromFile = new Scanner(file);
}
}
Starting with your example code...
import java.io.File;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI() {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
System.out.println(file.exists());
Scanner fromFile = new Scanner(file);
}
}
You are getting a compiler error because Scanner(File) can throw a FileNotFoundException
You either need to catch the exception or re-throw it, for example...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
public class FileManipulations {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> runGUI());
}
public static void runGUI() {
JFileChooser chooser = new JFileChooser();
switch (chooser.showOpenDialog(null)) {
case JFileChooser.APPROVE_OPTION:
File file = chooser.getSelectedFile();
System.out.println(file.exists());
try (Scanner fromFile = new Scanner(file)) {
while (fromFile.hasNextLine()) {
String text = fromFile.nextLine();
System.out.println(text);
}
} catch (FileNotFoundException exp) {
exp.printStackTrace();
}
break;
}
}
}
You might also like to have a look at How to Use File Choosers and make sure you are checking the return result of showOpenDialog so you know how the dialog was closed
Also, have a look at The try-with-resources Statement for more details about how to manage your resources
I think your code is somewhat as follows :
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.*;
public class Solutiokn {
public static void main(String[] args) {
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(null);
File file = fileChoose.getSelectedFile();
System.out.println(file.exists());
try {
Scanner fromFile = new Scanner(file);
while(fromFile.hasNextLine())
System.out.println(fromFile.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Ok now this works just fine. Only point when I have issue is when I do not pick a file in the file chosser and just click cancel. When this happens the scanner itself is not created as value in "file" is null. I suggest adding a check manually to see if any file was selected or not like if(file==null) System.out.println("Please select a file"); or throw your own exception. If you don't probably a sudden nullPointerException will pop up.
Edit : As madProgrammer pointed out file.getName() would rather instead throw nullPointerException I tried changing it to file.exists() that still throws Exception if file was not selected. So instead maybe checking file==null is better. file.exists() checks if file denoted by this pathname exists but if we never inititalized it i.e just cancelled in file chooser then it does not help.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
fin.close();
}
}
Around the Scanner portion I cant seem to fix the error.
It says File cant be resolved to a type.
And the file cant be found.
You are missing an import java.io.File; statement. Since you did not import this class (and since your code is not located in the java.io package), Java can't recognize it.
You have a type in your code. You code should be:
FileReader fin = new FileReader(new File("running.txt"));
^^^^^^^^^^^^^^
You can't store instance of File within FileReader.
Also the error that you see is because you have not imported java.io.File, so you need to import File like:
import java.io.File;
A side note: You will need to handle FileNotFoundException.
Try importing java.io.File, and change your FileReader line to the following:
FileReader fin = new FileReader(new File("running.txt"));
It compiled fine for me.
Use the following code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class running{
public static void main(String args[]) throws IOException {
double sum=0.0;
double num=0.0;
FileReader fin = (new File("running.txt");
Scanner src = new Scanner(fin);
try{
while (src.hasNext()){
if(src.hasNextDouble()){
num=src.nextDouble();
sum=sum+num;
System.out.println(sum);
}else{
break;
}
}
}catch(Exception e){}finally{fin.close();}
}
}
I am trying to write to a file to create a JAR.
But I am having problem with NullPointerException. My files are in Classpath.
(I use getClass() because I will be creating a JAR file. )
Any reason I would get a NullPointerException here? Thanks for your help.
Here is the code:
package Library;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URISyntaxException;
public class WriteJARSample {
public WriteJARSample() throws URISyntaxException, FileNotFoundException, FileNotFoundException, IOException{
write();
}
public void write() throws URISyntaxException, FileNotFoundException, IOException{
try{
File Mf=new File(getClass().getClassLoader().getResource("AllBookRecords.txt").toURI());
File Tf=new File(getClass().getClassLoader().getResource("Boutput.txt").toURI());
BufferedReader Bbr=new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("AllBookRecords.txt")));
PrintWriter Bpw=new PrintWriter(Mf);
String Bs;
while( (Bs=Bbr.readLine()) != null ){
Bpw.println(Bs);
}
Bpw.close();
Bbr.close();
Mf.delete();
Tf.renameTo(Mf);
}
catch(IOException ioe){
}
catch(URISyntaxException urise){
}
}
public static void main(String[] args) throws URISyntaxException, FileNotFoundException, IOException{
new WriteJARSample();
}
}
getClass().getResourceAsStream("AllBookRecords.txt") differs for the prior access of "AllBookRecords.txt", maybe it should also be:
getClass().getClassLoader().getResourceAsStream("AllBookRecords.txt")
or simply
getClass().getResourceAsStream("/AllBookRecords.txt")
getClass().getResource(AsStream) works relative to the class package (subdirectory).