How to read file? java [duplicate] - java

This question already has answers here:
Reading a plain text file in Java
(31 answers)
Closed 4 years ago.
I have created a class that has the features of reading and writing to a file even parsing what is in the file. But when I run my test, I am not able to read the file. This is the snippet of what I have, if it is not enough I can post the rest of what I have to help.
this is what my main looks like:
public static void main(String args[]) throws IOException {
String fileLocation = File.separator + "Users" + File.separator + "Desktop" + File.separator + "test.txt";
File file = new File(fileLocation);
DataStorage data = new DataStorage(fileLocation);
data.read();
}
this is what my read method looks like:
public File file;
public DataStorage(String filePath) {
setFile(filePath);
}
public Data read() throws IOException {
Data db = new Data();
Scanner scan = new Scanner(file);
Person person;
//check if file has data print selected data
while(scan.hasNextLine()) {
person = parsePerson(scan.nextLine());
db.add(person);
}
if(scan != null) {
// close() may throw IOException if fails;
scan.close();
}
return db;
}

Instead of filePath, you need to pass the file object as an Argument and the path which you are sending is incorrect in the main method "C DRIVE IF WINDOWS" otherwise starts with \ i.e, File.separator for Mac
public class Stackex1 {
public static void main(String args[]) throws IOException {
String fileLocation = "C:"+ File.separator + "Users" + File.separator + "USERNAMEGOESHERE" + File.separator + "Desktop" + File.separator + "test.txt";
System.out.println(fileLocation);
File file = new File(fileLocation);
DataStorage data = new DataStorage(file);
data.read();
}
}
class DataStorage {
public File file;
public DataStorage(File file) {
setFile(file);
}
public void setFile(File file) {
this.file = file;
}
.... //Remaining code goes here

Related

Terminal input gives null pointer but IDE input runs fine

Trying to build a program that changes stuff in SRC folder. for (File f : files) { Returns a null pointer despite returning appropriate answer in Intellij IDE. This program searches my SRC file directory and lists all files pertaining to the the directory. It works fine in the IDE but does not do the correct function on the command line.
//This program is from Liang Comprehensive Java 12.18
import java.io.*;
import java.util.ArrayList;
public class AddStatement {
public static void main(String[] args) throws IOException {
// File dir = new File(args[0]);
File dir=new File("src");
System.out.println(dir.getCanonicalPath() + " Was put into console");
writeTofile(getfiles(dir));
}//End of main class
public static ArrayList<String> getfiles(File dirc) throws IOException {
ArrayList<String> paths = new ArrayList<String>(5);
File[] files = dirc.listFiles();
for (File f : files) { //This part is where null is happening
paths.add(f.getCanonicalPath());
}//End of foreach
return paths;
}//End of getFiles method
public static void writeTofile(ArrayList<String> files) throws IOException {
String file;
int count = 1;
for (String f : files) {
file = f;
try (PrintWriter writer = new PrintWriter(new FileWriter(file, true))) {
if (file.contains("Chapter")) {
writer.print("\\\\Chapter" + count);
count++;
}//End of filtering if
}//End of try block
}//End of for loop
System.out.println("Files written");
}//End writeTofile
}// End of Class

Java: Getting FileNotFoundException when trying to read from a text file even though the file exists

I'm trying to read from a .txt file that is located in src\main\java\props\engprops.txt. I'm using backslashes here because I'm using Windows.
When I try to read the file I get a FileNotFoundException.
This is my helper class. It contains a method for returning a string representation of the directory in which the file is located. Here is what it returns C:\Users\SOME_USER\workarea\Myapp\myapp\src\main\props\
private final static String APP_HOME = "\\workarea\\Translate\\translate\\src\\main";
private final static String PROPS_HOME = "\\props\\";
public static String getPropsPath() {
StringBuilder sb = new StringBuilder();
String userHome = System.getProperty("user.home");
//userHome = userHome.replace("\\", "/");
String propsHome = null;
propsHome = userHome + APP_HOME + PROPS_HOME;
return propsHome;
}
Then in my main class is where I try to read the file:
private static String stringPath = AppHelper.getPropsPath();
public static void main(String[] args) {
readFile();
}
public static void readFile() throws IOException {
FileReader fReader = new FileReader(stringPath + "engprops.txt");
BufferedReader bReader = new BufferedReader(fReader);
String line = null;
while((line = bReader.readLine()) != null) {
System.out.println(line);
}
bReader.close();
}
Inside the readFile() method, I am appending the name of the file on to the stringPath variable with the file name being engprops.txt.
Here is a snippet of the console displays after the program executes; java.io.FileNotFoundException: C:\Users\600010209\workarea\Translate\translate\src\main\props\engprops.txt (The system cannot find the file specified)
You wrote in your question that your file was located under src/main/java/props, but the props path you declared was under src/main/props.
Comment if that doesnt answer your question.

How to concatenate files from an array to into a new folder? [duplicate]

This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
Closed 6 years ago.
I am trying to write a java program that will take two arguments, dirName and fileName. The program will search for all the files in dirName that end with .java and then concatenate them into a new folder called fileName. So far I have a method to search for .java files in dirName, I then put them in a file array called list but now I am struggling to iteratively add the files in this array to my new folder, fileName. Here is what I have so far:
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class TwoFiles {
File dir;
File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public File[] Finder(File dir) {
dir = getDir();
return dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return name.endsWith(".java"); }
} );
}
public static void main(String[] args) {
File folder = null;
File newFolder = null;
Integer b = null;
TwoFiles tf = new TwoFiles(folder, newFolder);
folder = tf.getDir();
newFolder = tf.getNewFolder();
File[] list = tf.Finder(folder); //add to an array
//here is where I've been experimenting to add files in `list` to new folder, `fileName`.
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
newFolder.write(b);
inFile.close();
}
//copy files from array (list) into newFolder
}
}
Thanks for your time.
Your newFolder variable is of type File. You cannot write into this. I assume, your code does not even compile. You have to create an output stream in front of your loop:
FileOutputStream fos = new FileOutputStream( newFolder);
try
{
for (File file : list)
{
FileInputStream inFile = new FileInputStream(file);
while ((b = inFile.read()) != -1)
fos.write(b);
inFile.close();
}
}
finally
{
fos.close();
}
You can use the Apache Commons IO copyDirectory() with the IOFileFilter (for .java extensions) to copy your files from one directory to another. Before that you can ensure to create a new directory using forceMkdir() for your filename.
It's my version of your problem:
I created other constructor, where you can put only paths to directory/folder from you want concatenate files, and to file of concatenations result.
public class TwoFiles {
private File dir;
private File name;
public TwoFiles(File dirName, File fileName) {
dir = dirName;
name = fileName;
}
public TwoFiles(String dirName, String destinationFileName) throws IOException{
dir=new File(dirName);
if(!dir.isDirectory()){
throw new FileNotFoundException();//here your exception in case when dirName is file name instead folder name
}
name=new File(destinationFileName);
if(!name.exists()){
name.createNewFile();
}
}
public void setDir(File m) {
this.dir = m;
}
public File getDir() {
return dir;
}
public void setNewFolder(File n) {
this.name = n;
}
public File getNewFolder() {
return name;
}
public void concatenateFiles() throws IOException{
File[] files=dir.listFiles();
for(File file: files){
if(file.getName().endsWith(".java")){ //check is right file
prescribe(name, file);
}
}
}
/** prescribe file to new destination */
private void prescribe(File destination, File file) throws IOException {
FileInputStream inFile = new FileInputStream(file);
FileOutputStream writer=new FileOutputStream(destination, true); //true means next file will be write beginning from end of the file
int x;
while((x=inFile.read())!=-1){
writer.write(x);
}
String test="\n"; //next line in file
writer.write(test.getBytes());
writer.close();
inFile.close();
}
public static void main(String...strings){
String dirName="C/myApp/model/entity";
String fileName="C:/Users/Dell/Desktop/temp/test.java";
try {
new TwoFiles(dirName, fileName).concatenateFiles();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

how to search subfolders and files to get input form the user using java

how to search subfolders and files to get input form the user using java,
using listRoot method, but how to use with give a File class path
use recursion on the top directory.Some thing as shown below
class Main{
public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Folder is " + file.getName());
showFiles(file.listFiles());
} else {
System.out.println("File is " + file.getName());
}
}
public static void main(String[] args) {
File[] files = new File("your path").listFiles();
showFiles(files);
}}
}

Creating files on disk from a jar

My problem is that whenever I run my program from Eclipse or IntelliJ I can create as many files in a specific folder but when I create a jar it only creates one file no matter how many times I call the method that does this.
In detail a feature of a program allows the user to create a file in the folder where the jar is executed from. This is done through a class containing static fields and methods.
The fields in the class are:
private static StringBuilder sb = new StringBuilder();
private static Formatter formatter = new Formatter(sb);
private static BufferedWriter bw;
private static String filesFolderPath;
First I get the path to the jar:
private static String getJarPath() throws UnsupportedEncodingException
{
URL url = PrintHelper.class.getProtectionDomain().getCodeSource().getLocation();
String jarPath = URLDecoder.decode(url.getFile(), "UTF-8");
String path = new File(jarPath).getParentFile().getPath();
return path;
}
Then I set the path to the folder I want the files to be put in and create that folder through a static block in the class so that this code is executed only once when the class is first used:
static
{
try
{
String dirPath = getJarPath();
String fileSeparator = System.getProperty("file.separator");
filesFolderPath = dirPath + fileSeparator + "files" + fileSeparator;
File file = new File(filesFolderPath);
file.mkdir();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
Finally. each time a user wants to create a file this method is called:
public static void print(String filename) throws IOException, FileNotFoundException
{
File file = new File(filesFolderPath, getFileName(filename));
bw = new BufferedWriter(new FileWriter(file));
//writing with the buffered writer
bw.close();
}
Is there any reason for this to work as I want it when run from an IDE and create only one file when running from the jar?

Categories