am I still very new to java, only had one semester of it. I have my first internship and it isn't a programming internship, just a general IT internship Since it was only my first semester.
My boss does not know Java, nor does anyone in the building. He knew I had some basic programming experience and told me to take a stab at the problem he is having. He has a report that is saved and the very last line, the very last character of the report is a character turn symbol, and we need remove that because it is giving us problems on the website.
I am not sure if I am even on the right track, at this point I am just doing trial and error. Please help :D
public class RemoveChar {
public static void main(String[] args) throws FileNotFoundException {
// Variables and stuff
Scanner keyScan = new Scanner(System.in);
JFrame frameOne = new JFrame ("File Name");
Scanner fileScan = new Scanner(System.in);
String fileName;
// Ask user for file name
System.out.print("What is the file full file name? ");
fileName = fileScan.nextLine();
// Add .txt if the user forgets to put it in the prompt
if (!fileName.contains(".txt"))
fileName += ".txt";
//Test to see if file exists
File myFile = new File(fileName);
if(!myFile.exists()){
System.out.println(fileName + " does not exist. ");
System.exit(0);
}
fWriter = new FileWriter("config/lastWindow.txt", true);
/*while(fileName.hasNext()){
}
File
BufferedReader inputFile = new BufferedReader(new FileReader("C:\\" + fileScan));
//Scanner reader = new Scanner (inputFile);
*/
}
}
How big are the files? If they are not that large, you can read the entire file into a string and then chop off the last character:
//Set delimiter to end-of-string anchor \Z so that you can read the
//file in with just one call to next()
//from: http://stackoverflow.com/a/3403112/263004
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
String withoutLastCharacter = content.substring(0, content.length - 1);
Then you just need to write withoutLastCharacter out to the file.
Otherwise you need to read in the original file line by line and write it out to a temporary file, and then copy that file over the original one. However, if you are on the last line, you will chop off the last character. Here's some code that should give you an idea of the basic logic:
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
//If this is the last line chop off the last character.
if(!scanner.hasNextLine()) {
line = line.substring(0, line.length - 1);
}
//Write line out to temporary file
...
}
You also mentioned that it doesn't have to be Java. If you're on Linux or Mac, you can just do this with sed:
sed -i '$s/.$//' <filename>
This will delete the last character of the last line of the file.
Does this have to be a java problem? For something like this where it is basic file/string manipulation I prefer to use something like Perl. The below perl script will delete the last byte (or char in this case) from a file
my $fsize = -s $filename;
# print $size."\n";
open($FILE, "+<", $filename) or die $!;
seek $FILE, $size-2, SEEK_SET;
print $FILE ";";
close $FILE;
static class CopyFileContent {
public static void main(String[] args) {
String root = Environment.getExternalStorageDirectory().toString(); //get access to directory path
File myDir = new File(root + "/MyFolder");//create folder in internal storage
myDir.mkdirs();// make directory
File destFile = new File(myDir, FILENAME11);//making a new file in the folder
/* Source file, from which content will be copied */
File sourceFile1 = new File(myDir, FILENAME12);
File sourceFile2 = new File(myDir, FILENAME13);
File sourceFile3 = new File(myDir, FILENAME14);
/* destination file, where the content to be pasted */
// File destFile = new File(FILENAME);
/* if file not exist then create one */
if (!destFile.exists()) {
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;
OutputStream output = null;
InputStream input4 = null;
try {
/* FileInputStream to read streams */
input1 = new FileInputStream(sourceFile1);
input2 = new FileInputStream(sourceFile2);
input3 = new FileInputStream(sourceFile3);
/* FileOutputStream to write streams */
output = new FileOutputStream(destFile, true);
byte[] buf = new byte[1024];
int bytesRead;
output.write("{Record:[{".getBytes());
while ((bytesRead = input1.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input2.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
}
while ((bytesRead = input3.read(buf)) > 0) {
output.write(buf, 1, bytesRead);
RandomAccessFile f = new RandomAccessFile(destFile, "rw");
long length = f.length() - 2;
f.setLength(length);
length = f.length();
f.close();
output.write(",".getBytes());
output.write(b.getBytes());
output.write(d.getBytes());
output.write("}]}".getBytes());
output.write("\r\n".getBytes());
}
RandomAccessFile f1=new RandomAccessFile(destFile,"rw");
long length1= f1.length()-1;
f1.setLength(length1);
f1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != input1) {
input1.close();
}
if (null != input2) {
input2.close();
}
if (null != input3) {
input3.close();
}
if (null != output) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Related
I made a program that can display and edit a record. The problem is that I cannot delete the file that I wanted to delete to replace it with the edited ones.
public class Laboratory {
public static void main(String[] args) throws FileNotFoundException,InterruptedException,IOException {
// paste your script here ;)
String fileName = "record.txt";
String filepath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + fileName;
String in = "";
File file = new File(filepath);
Scanner fscan = new Scanner(file);
Scanner scan = new Scanner(System.in);
PrintWriter pw = null;
int linecount = 1;
String content = "";
// reads the file according to the given line count.
for(int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
// creates the template file.
String tempPath = "D:\\Programming\\Java\\Program - Script Test\\files\\" + "temp.txt";
String contentParts[] = content.split("\\|");
System.out.println(content);
System.out.println(contentParts[1]);
System.out.println(contentParts[2]);
System.out.print("change the name >> ");
in = scan.nextLine();
// edits the scanned content from the file.
String finalContent = "|" + in + "|" + contentParts[2];
System.out.println(finalContent);
file = new File(filepath);
fscan = new Scanner(file);
// scans the original record and pastes it in a new template file.
try {
pw = new PrintWriter(new FileOutputStream(tempPath));
if(linecount == 1) {
content = fscan.nextLine();
pw.println(finalContent);
while(fscan.hasNextLine()) {
content = fscan.nextLine();
pw.println(content);
}
}
else if (linecount > 1) {
for (int i = 0; i < linecount - 1; i++) {
content = fscan.nextLine();
pw.println(content);
}
pw.println(finalContent);
content = fscan.nextLine();
while (fscan.hasNextLine()) {
content = fscan.nextLine();
pw.println(content);
}
}
}
catch(FileNotFoundException e) {
System.out.println(e);
}
finally {
pw.close();
fscan.close();
}
// deletes the original record
file.delete();
} // end of method
} // script test class end
Although, I made a test program that successfully deletes a file.
public class delete {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
File file = new File("helloworld.txt");
String in;
System.out.println("Press ENTER to DELETE file.");
in = scan.nextLine();
file.delete();
} // main method end
} // program end
My file path is right and I don't really know what causes the problem. Is there a solution to fix this?
Explanation
file.delete() does not throw an error if it failed. And it failed here, as indicated by its return value being false.
Execute Files.delete(file.toPath()) instead and you will see the exact error reason, which is:
Exception in thread "main" java.nio.file.FileSystemException: D:\Programming\Java\Program - Script Test\files\record.txt: The process cannot access the file because it is being used by another process
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:92)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:274)
at java.base/sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:105)
at java.base/java.nio.file.Files.delete(Files.java:1146)
at Laboratory.main(Laboratory.java:123)
So
The process cannot access the file because it is being used by another process
Because you still have a scanner to the file open, you are blocking yourself from deleting it. Close the scanner and it will work.
Your code opens two (not one) scanner to file, one at the beginning:
Scanner fscan = new Scanner(file);
which you use during your initial loop:
for (int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
and then later on you create a second one:
fscan = new Scanner(file);
which you also close during your finally block:
fscan.close();
But you did never close the first scanner.
Solution
Add
fscan.close();
After the initial loop:
for(int i = 0; i < linecount; i++) {
content = fscan.nextLine();
}
fscan.close();
and the file.delete() will succeed.
NIO
As explained, file.delete() is a poorly designed method. Prefer Files.delete(path).
In general, if you do not have a good reason to use the old cumbersome file IO library, dont. Use NIO instead (Java 7+).
Hello so i have an assignment and my code is not working. I ask a user to input a filename and after that it freezes and does not process the number of lines. im doing something wrong but im not sure what? can someone please help me im really desperate this part is crashing my whole program and i might fail and i dont know who to ask :( for help
public static void fileReader()
{
Scanner sc = new Scanner(System.in);
int catNum;
int dogNum;
int fishNum;
String fileName;
System.out.println("Please enter the Name of the file you want to read in
from");
fileName = sc.nextLine();
System.out.println("this is the file name --> "+fileName);
catNum = TestFile.getNum(fileName, "cat");
dogNum = TestFile.getNum(fileName, "dog");
fishNum = TestFile.getNum(fileName, "fish");
System.out.println("THE CAT IS" +catNum);
System.out.println("THE DOG IS" +dogNum);
System.out.println("THE FISH IS" +fishNum);
}
i dont see anything wrong after i ask for the file name it freezes
public static int getNum (String fileName, String word) {
Scanner sc = new Scanner(System.in);
int lineNum = 0;
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
try {
fileStrm = new FileInputStream (fileName);
rdr = new InputStreamReader (fileStrm);
bufRdr = new BufferedReader (rdr);
line = bufRdr.readLine();
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
fileStrm.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch(IOException ex2)
{
System.out.println("This is Error");
}
}
System.out.println("error reading file !!" +e.getMessage());
}
return lineNum; }
the file looks something like this (each line is like this):
CAT:NAME=doopie:SHORTNAME=doop:LANGUAGE=English:AREA=America:POPULATION=2222:POPREF=Census2016
Look at this while loop:
while (line != null)
{
String firstWord = processString(line);
if(firstWord.equalsIgnoreCase(word)) //this submodule i going to get the number to create each array like e.g. how many states so that it can create it in country object
{
lineNum++;
line = bufRdr.readLine() ;
}
}
If firstWord.equalsIgnoreCase(word) returns false, then what will happen? The value of line will never be updated and the loop will never exit.
I would like some help with a project that I am working on. I want to create a simple program that formats data into a way that is accepting of our database. I am having trouble copying the contents of the main file to the destination file. The program creates the new destination file and it writes the "Gage ID, Date/Time, Precip_1min, Precip/Year" headers in the file but there are no data values copied to the new file. I have tried to look online for some solutions but, I have had no luck in applying these solutions. The main thing that I am concentrating on is copying each line of the main file to the new created file one-by-one then I will work from there. Any assistance is very much appreciated! Here is my code so far. P.S Cowlic105.txt is the file that has the lines of data that I want to be copied.
import java.io.*;
import java.util.Scanner;
public class MyDataFormat {
public static void main(String[] args) {
String fileName = "Cowlic105.txt";
String fileName2 = "FormDatFile.txt";
String line = null;
int x;
int gageID;
int precipYTD;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
Scanner in = new Scanner(System.in);
System.out.println("Is this the file you wish to format? " + fileName + "(0 for no, 1 for yes)");
x = in.nextInt();
if (x == 0){
System.exit(0);
}
else if (x == 1){
System.out.println("Hello there you resumed the program!!!");
System.out.println("What is the ID of the rain gage? ");
gageID = in.nextInt();
System.out.println("What is the value of precipitation YTD? ");
precipYTD = in.nextInt();
File destFile = new File("FormDatFile.txt");
if(!destFile.exists()){
try {
destFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileInputStream fis = new FileInputStream(destFile);
FileWriter writer = new FileWriter(destFile, true);
BufferedWriter write2 = new BufferedWriter(writer);
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
while((line = bufferedReader.readLine()) != null){
write2.write(line);
write2.newLine();
bufferedReader.close();
write2.close();
}
writer.write("Gage ID,Date/Time,Precip_1min,Precip/Year");
writer.write("\r\n");
writer.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
I have to accomplish a task of writing a set of data to file, use it, then overwrite it with new data. Thus overwrite of the file takes place repeatedly.I know i can accomplish the above by creating FileWriter object each time with the option to overwrite like below
FileWriter object = new FileWriter("fileName", false)
and close it to write to the file.
If i am supposed to overwrite the file n number of times , according to the above method i need to create n number of FileWriter objects. Is there any efficient way to overwrite a file repeatedly by only creating a single FileWriter object?
Not a direct answer, but anyway.
DON'T DO THAT!
What do you think will happen if for some reason writing the new data to the file fails?
You not only lose your original file, but also the new file contents...
Write the new content to another file, ensure that it is well written and closed, and then rename the new file atomically to the original file.
PS: and do not forget to correctly .close().
PS2: if you use Java 7, use the new Files API.
Its better to make a temp file and then rename the tempfile and delete the old like here:
public static void nachtragenTRA(File files) throws IOException{
Scanner sc=null;
File f= files;
String analyse = "";
String NTausgabe = "";
int max = 0;
int k = 0;
String updatedLine[] = new String [4];
int filenr = 1;
boolean sucess = false;
try{
sc= new Scanner(f);
}catch(FileNotFoundException x){
System.out.println("Error: File not found!");
}
while (sc.hasNextLine()){ //get next line
analyse = sc.nextLine();
max = analyse.length(); //get line lenght
StringBuffer sb = new StringBuffer(analyse); //write analyse in StringBuffer
//to change the string
if(k == 1)
{
sb.replace(Daten.NTdatapos[3],max, Daten.NTProbentypTextfield.getText());
updatedLine[0] =String.valueOf(sb);
}
else if(k == 2)
{
sb.replace(Daten.NTdatapos[4],max, Daten.NTPrueferTextfield.getText());
updatedLine[1] =String.valueOf(sb);
}
else if(k == 3)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTKundeTextfield.getText());
updatedLine[2] =String.valueOf(sb);
}
else if(k == 4)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTWerkstoffTextfield.getText());
updatedLine[3] =String.valueOf(sb);
}
if(k>3)
{
break;
}
k++;
}
sc.close();
//NTausgabe=DatenTextarea.getText()+"\n"+updatedLine[0]+"\n"+updatedLine[1];
//DatenTextarea.setText(String.valueOf(NTausgabe));
//NTausgabe=DatenTextarea.getText()+"\n"+NTKundeTextfield.getText()+"\n"+NTPrueferTextfield.getText();
//DatenTextarea.setText(String.valueOf(NTausgabe));
//create tmp file with the new data
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(String.valueOf(f)+".tmp")));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader(String.valueOf(f));
br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null)
{
//Change speciffic lines
if(filenr == 2)
{
writer.println(updatedLine[0]);
}
else if(filenr == 3)
{
writer.println(updatedLine[1]);
}
else if(filenr == 4)
{
writer.println(updatedLine[2]);
}
else if(filenr == 5)
{
writer.println(updatedLine[3]);
}
//Andere Zeilen beibehalten
else
{
writer.println(line);
}
filenr = filenr + 1;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
br.close();
File realName = new File(String.valueOf(f));
realName.delete(); //delete old file
writer.close();
sucess = new File(String.valueOf(f)+".tmp").renameTo(realName); //rename tmp File to the others name
if(sucess != true)
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"Rename File failed";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
else
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"File renamed sucessfully";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
}
}
I have a directory that contains sequentially numbered log files and some Excel spreadsheets used for analysis. The log file are ALWAYS sequentially numbered beginning at zero, but the number of them can vary. I am trying to concatenate the log files, in the order they were created into a single text file which will be a concatenation of all the log files.
For instance, with log files foo0.log, foo1.log, foo2.log would be output to concatenatedfoo.log by appending foo1 after foo0, and foo2 after foo1.
I need to count all the files in the given directory with the extension of *.log, using the count to drive a for-loop that also generates the file name for concatenation. I'm having a hard time finding a way to count the files using a filter...none of the Java Turtorials on file operations seem to fit the situation, but I'm sure I'm missing something. Does this approach make sense? or is there an easier way?
int numDocs = [number of *.log docs in directory];
//
for (int i = 0; i <= numberOfFiles; i++) {
fileNumber = Integer.toString(i);
try
{
FileInputStream inputStream = new FileInputStream("\\\\Path\\to\\file\\foo" + fileNumber + ".log");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
try
{
BufferedWriter metadataOutputData = new BufferedWriter(new FileWriter("\\\\Path\\to\\file\\fooconcat.log").append());
metadataOutputData.close();
}
//
catch (IOException e) // catch IO exception writing final output
{
System.err.println("Exception: ");
System.out.println("Exception: "+ e.getMessage().getClass().getName());
e.printStackTrace();
}
catch (Exception e) // catch IO exception reading input file
{
System.err.println("Exception: ");
System.out.println("Exception: "+ e.getMessage().getClass().getName());
e.printStackTrace();
}
}
how about
public static void main(String[] args){
final int BUFFERSIZE = 1024 << 8;
File baseDir = new File("C:\\path\\logs\\");
// Get the simple names of the files ("foo.log" not "/path/logs/foo.log")
String[] fileNames = baseDir.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".log");
}
});
// Sort the names
Arrays.sort(fileNames);
// Create the output file
File output = new File(baseDir.getAbsolutePath() + File.separatorChar + "MERGED.log");
try{
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(output), BUFFERSIZE);
byte[] bytes = new byte[BUFFERSIZE];
int bytesRead;
final byte[] newLine = "\n".getBytes(); // use to separate contents
for(String s : fileNames){
// get the full path to read from
String fullName = baseDir.getAbsolutePath() + File.separatorChar + s;
BufferedInputStream in = new BufferedInputStream(new FileInputStream(fullName),BUFFERSIZE);
while((bytesRead = in.read(bytes,0,bytes.length)) != -1){
out.write(bytes, 0, bytesRead);
}
// close input file and ignore any issue with closing it
try{in.close();}catch(IOException e){}
out.write(newLine); // seperation
}
out.close();
}catch(Exception e){
throw new RuntimeException(e);
}
}
This code DOES assume that the "sequential naming" would be zero padded such that they will lexigraphically (?? sp) sort correctly. i.e. The files would be
0001.log (or blah0001.log, or 0001blah.log etc)
0002.log
....
0010.log
and not
1.log
2.log
...
10.log
The latter pattern will not sort correctly with the code I have given.
Here's some code for you.
File dir = new File("C:/My Documents/logs");
File outputFile = new File("C:/My Documents/concatenated.log");
Find the ".log" files:
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File file, String name) {
return name.endsWith(".log") && file.isFile();
}
});
Sort them into the appropriate order:
Arrays.sort(files, new Comparator<File>() {
#Override
public int compare(File file1, File file2) {
return numberOf(file1).compareTo(numberOf(file2));
}
private Integer numberOf(File file) {
return Integer.parseInt(file.getName().replaceAll("[^0-9]", ""));
}
});
Concatenate them:
byte[] buffer = new byte[8192];
OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
for (File file : files) {
InputStream in = new FileInputStream(file);
try {
int charCount;
while ((charCount = in.read(buffer)) >= 0) {
out.write(buffer, 0, charCount);
}
} finally {
in.close();
}
}
} finally {
out.flush();
out.close();
}
By having the log folder as a File object, you can code like this
for (File logFile : logFolder.listFiles()){
if (logFile.getAbsolutePath().endsWith(".log")){
numDocs++;
}
}
to find the number of log files.
I would;
open the output file once. Just use a PrintWriter.
in a loop ...
create a File for each possible file
if it doesn't exist break the loop.
Using a BufferedReader
to read the lines of the file with readLine()
write each line to the output file.
You should be able to do this with about 12 lines of code. I would pass the IOExceptions to the caller.
You can use SequenceInputStream for concatenation of FileInputStreams.
To see all log files File.listFiles(FileFilter) can be used.
It will give you unsorted array with files. To sort files in right order, use Arrays.sort.
Code example:
static File[] logs(String dir) {
File root = new File(dir);
return root.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".log");
}
});
}
static String cat(final File[] files) throws IOException {
Enumeration<InputStream> e = new Enumeration<InputStream>() {
int index;
#Override
public boolean hasMoreElements() {
return index < files.length;
}
#Override
public InputStream nextElement() {
index++;
try {
return new FileInputStream(files[index - 1]);
} catch (FileNotFoundException ex) {
throw new RuntimeException("File not available!", ex);
}
}
};
SequenceInputStream input = new SequenceInputStream(e);
StringBuilder sb = new StringBuilder();
int c;
while ((c = input.read()) != -1) {
sb.append((char) c);
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
String dir = "<path-to-dir-with-logs>";
File[] logs = logs(dir);
for (File f : logs) {
System.out.println(f.getAbsolutePath());
}
System.out.println();
System.out.println(cat(logs));
}