concatenating .java files in java - java

so I'm making a java app to find all java files on a directory and then concatenate them into one single file to be put on the same directory but I can't seem to get the concatenation right. Here's what I've done so far hope you guys can help me with it as I've tried various things but still can't get it right. Thanks!
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileConcatenate {
public static void main(String[] args) {
String dirName = args[0];
String fileName = args[1];
File dirFile = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "");
File file = new File("C:\\Users\\Michael\\Desktop\\" + dirName + "\\" + fileName + ".java");
FileFilter filter = new FileFilter(){
public boolean accept(File pathname){
if(pathname.getName().contains(".java")){
return true;
}else{
return false;
}
}
};
try{
if(!dirFile.exists()){
System.out.println("There is no directory with that name");
}
File[] javaFile = dirFile.listFiles(filter);
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
for(File f : javaFile){
FileReader fr = new FileReader(f);
fw.write(fr.read());
fr.close();
}
fw.flush();
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
}

Do in this way. For more info read inline comments.
...
FileWriter fw = new FileWriter(file, true);
for (File f : javaFile) {
FileReader fr = new FileReader(f);
// read 1000 chars at a time from source file
char[] cbuf = new char[1000];
int count = -1;
// iterate till the end of source file
// here count represent the no of chars read at a time
while ((count = fr.read(cbuf)) != -1) {
// write in the targeted file
fw.write(cbuf, 0, count);
}
fr.close();
}
...
In your case fw.write(fr.read()); doesn't do what you are expecting.
It just read one character form the source file and write in the target file.
For more info have a look at InputStreamReader#read() that reads a single character.

Related

Java txt parser new line issue

Good Morning. Having trouble with a parser using split method. Goal is to read in txt file, extract should statements, then write a new txt file with those should statements. I have it working when the text is on one continuous line. If I have a new line in the txt file, rewrites the file with just the last line. Possibly the structure of my loops? Also any suggestions for saving new file from the directory in which it was opened? Thank you
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/*This Program Will launch a File Explorer.
User will then chose a .txt file to be parsed.
A new file will be created labeled "Parsed_(Document Name)".*/
public class Parser {
#SuppressWarnings("resource")
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
Scanner userFile = new Scanner(System.in);
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName() + "\n");
File file = new File(chooser.getSelectedFile().getName());
String newFile = ("Parsed_" + file);
userFile = new Scanner(file);
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
List<String> ShouldArray = new ArrayList<String>();
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
FileWriter writer = new FileWriter(newFile);
BufferedWriter bw = new BufferedWriter(writer);
for (String shallStatements : ShouldArray) {
System.out.println(shallStatements);
bw.append(shallStatements);
bw.newLine();
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
bw.close();
writer.close();
}
userFile.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
Test file 1 (works!)
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
Test file 1 output:
You Should have a toothbrush
You Should have a Phone charger
And you definitely should have your wallet
Test file 2 (Only printing last line)
Hello all. Here is a a packing list. You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
test file 2 output:
You definitely should have your wallet
You need to create your result array outside of the loop
/** Placed here**/
List<String> ShouldArray = new ArrayList<String>();
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
/** REMOVED HERE **/
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should"))
ShouldArray.add(shouldStatements);
}
......
otherwise you will only gather the results of your last loop.
Basically what your code was doing:
cut up file in lines
take each line
take next line
make a result board.
write results on board
take next line
erase board
write results on board
take next line
erase board
write results on board
and then at the end there is only a limited resultset on your board
You are overriding your Arraylist within the loop, however you don't actually need it
File file = chooser.getSelectedFile();
System.out.println("You chose to open this file: " + file.getName() + "\n");
String newFile = "Parsed_" + file.getName();
// open all closable objects using try-with-resources
try (Scanner userFile = new Scanner(file);
BufferedWriter bw = new BufferedWriter(new FileWriter(newFile))) {
while (userFile.hasNextLine()) {
String document = userFile.nextLine();
// Line breaks used by Parser
String[] sentences = document.split("\\.|\\?|\\!|\\r");
for (String s : sentences) {
if (s.contains("Should") || s.contains("should")) {
System.out.println(s);
bw.append(s);
bw.newLine();
}
}
System.out.println("\nParsed Document Created: " + newFile);
JOptionPane.showMessageDialog(null, "Parsed Document Created: " + newFile);
// bw.close(); // not needed anymore
I've refactored the code, removing the "ShouldArray", which is not needed.
Pseudocode
While there are lines to read in the In file
Read each line
Split each line into Array of sentences
Loop through each sentence
If each sentence contains Should or should Then
Write sentence to Out file
End If
End Loop
End While
Close Out file
Close In file
The code below works with:
Multi line:
Hello all. Here is a a packing list.
You Should have a toothbrush. You Should have a Phone charger.
Here is some random text to show the parser will not include this.
You definitely should have your wallet!
Single line:
Hello all. Here is a a packing list. You Should have a toothbrush. You should have a Phone charger. And you definitely should have your wallet!
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
public class ShouldStringsParser {
public ShouldStringsParser(String inFile, String outFile) throws IOException {
File file = new File(inFile);
FileWriter writer = new FileWriter(outFile);
BufferedWriter bw = new BufferedWriter(writer);
Scanner userFile;
userFile = new Scanner(file);
String[] sentences;
while (userFile.hasNextLine()) {
String line = userFile.nextLine();
System.out.println(line);
sentences = line.split("\\.|\\?|\\!|\\r");
for (String shouldStatements : sentences) {
if (shouldStatements.contains("Should") || shouldStatements.contains("should")) {
System.out.println(">>>" + shouldStatements);
bw.append(shouldStatements);
bw.newLine();
}
}
}
bw.close();
writer.close();
userFile.close();
}
public static void main(String[] args) {
try {
new ShouldStringsParser("inDataMultiLine.txt", "outDataMultiLine.txt");
new ShouldStringsParser("inDataSingleLine.txt", "outDataSingleLine.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Java Read / Write To File - BufferedReader BufferedWriter [duplicate]

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is a code snippet but basically what I want to do is read from a file named 'listings.txt' and write to a file named 'overview.txt'. I want to take the information out of 'listings.txt' and put them into 'overview.txt' as is (I will figure out the rest later).
The file 'overview.txt' is created and appears to loop through the file 'listings.txt' and write to 'overview.txt'. However, once I open the file 'overview.txt' it is empty. Could someone go through a quick glance at my code and spot something erroneous?
package yesOverview;
import java.io.BufferedReader;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class yesOverview {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strInput = "foo.bar";
System.out.print("Please enter the listings file (the full path to the file): ");
strInput = input.next();
//This makes sure that the inputed file is listings.txt as required for KET1 task 2
while (strInput.contains("listings.txt") == false) {
System.out.print("Incorrect file. Please enter listings file(the full path to the file): ");
strInput = input.next();
}
infos(strInput);
input.close();
}
public static void infos(String strInput) {
Scanner input2 = new Scanner(System.in);
System.out.print("Please enter the overview.txt file (the full path to the file): ");
String strInput2 = "foo.bar";
strInput2 = input2.next();
//This also makes sure that the overview.txt file is provided.
while (strInput2.contains("overview.txt") == false) {
System.out.print("Incorrect file. Please enter overview file(the full path to the file): ");
strInput2 = input2.next();
}
//Creates the file f then places it in the specified directory.
File f = new File(strInput2);
try {
//Creates a printerwriter out that writes to the output file.
PrintWriter out = new PrintWriter(strInput2);
} catch (FileNotFoundException ex) {
Logger.getLogger(KETTask2Overview.class.getName()).log(Level.SEVERE, null, ex);
}
//String that holds the value of the next line.
String inputLine = "";
//Creates the Buffered file reader / writer.
try {
BufferedReader in = new BufferedReader(new FileReader(strInput));
FileWriter fstream = new FileWriter(strInput2);
BufferedWriter out = new BufferedWriter(fstream);
while (in.readLine() != null) {
out.write(in.read());
}
in.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Try this
Close the BufferedWriter stream (ie out.close() )
try and use nextLine() instead of next(), as next() only takes in a single word, but for a complete line use nextLine(), though this doesnt seem to be the problem here.
What i do when i have to read and write to files, i normally follow these steps
For Reading from a file
File f = new File("my.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((br.readLine())!=null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
For Writing to a file:
Boolean isDone = true;
Scanner scan = new Scanner(System.in);
File f = new File("my.txt");
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while (isDone) {
if (!isDone) {
br.write(new Scanner(System.in).nextLine());
}
}
public static long copy (Reader input, Writer output) throws IOException {
char[] buffer = new char[8192];
long count = 0;
int n;
while ((n = input.read( buffer )) != -1) {
output.write( buffer, 0, n );
count += n;
}
return count;
}
Usage Example:
copy( reader, new FileWriter( file ) );
You're not closing out.
The finally block for the writeList method cleans up and then closes the BufferedWriter.
finally {
if (out != null) {
System.out.println("Closing BufferedWriter");
out.close();
} else {
System.out.println("BufferedWriter not open");
}
}

Java Program read input from a text file and modify it accordingly

I am writing a Java program that inputs a test file, performs some modifications to the data, then writes it to a new file output.
The input text file looks like this...
url = http://184.154.145.114:8013/wlraac name = wlr samplerate = 44100 channels =2 format = S16le~
url = http://newstalk.fmstreams.com:8080 name = newstalk samplerate = 22050 channels = 1 format = S16le
The program needs to be able to change the samplerate to 44100, and the channels to 1, if they don't already have these values. I would also remove the url and name pieces completely. After these changes, the new line needs to be written out to a different output text file.
So far, all my program can do is select a file and display the contents of the file to the user. Could someone please point me in the right direction for how my program should work
to achieve my required outcome.
As somebody asked here is what I have so far
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class reader2 {
public reader2() {
}
public static void main(String[] args) {
reader(args);
}
public static void reader(String[] args) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt")
|| f.isDirectory();
}
public String getDescription() {
return "Text Documents (.txt)";
}
});
int r = chooser.showOpenDialog(new JFrame());
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getName();
String pathToFIle = chooser.getSelectedFile().getPath();
System.out.println(name);
try{
BufferedReader reader = new BufferedReader( new FileReader( pathToFIle ) ); //Setup the reader
while (reader.ready()) { //While there are content left to read
String line = reader.readLine(); //Read the next line from the file
String[] tokens = line.split( "url = " ); //Split the string at every # character. Place the results in an array.
for (String token : tokens){ //Iterate through all of the found results
//System.out.println(token);
System.out.println(token);
}
}
reader.close(); //Stop using the resource
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
You will need to do something like this ...
Read the contents of the file, one line at a time
Split the line up into the individual components, such as splitting it on the 'space' character
Change the sample rate and channel values according to your question
Write the line out to a file, and start again from step 1.
If you give this a try, post some code on StackExchange with any problems and we'll try to assist.
can you try
File file = new File( fileName );
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
String line = br.readLine();
String newLine = line.replaceAll( "samplerate =\\s*\\d+", "samplerate = 44100");
newLine = newLine.replaceAll( "channels =\\s*\\d+", "channels = 1");
fw.write(newLine + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
Ref: Files java replacing characters

Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )

Ok, so im writing a program that transfers files from my usb to a computer (so i can set up stuff quickly for something im doing on monday) and im trying to make it make a shortcut on the desktop so that you dont have to go into the source folder of the files transfered so you can start up the program again in case you exit it. heres my code, and the title is the error im getting.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class Mover {
public static void main(String[] args) throws IOException, InterruptedException {
String usb = new File(".").getAbsolutePath();
String desktop = System.getProperty("user.home") + "/Desktop";
File srcFolder = new File(usb + "/Teamspeak 3");
File destFolder = new File(desktop + "/TS3");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
String cmd = "ls -al";
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
while ((line=buf.readLine())!=null) {
System.out.println(line);
Process process = Runtime.getRuntime ().exec (desktop + "/TS3/ts3client_win32.exe");
System.exit(0);
}
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
String line = "-shortcut -t c:/ocuments and Settings/%username%/Desktop/TS3/ts3client_win32.exe" "-n Teamspeak 3.lnk";
This line seems malformed. You have two strings without + in between.

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