Error in reading first element from csv file - java

I am trying to read a rectangle.csv file in Java. But while I was reading the file and assigning to a string array, the first element is reading some garbage value along with the first element.
package sample;
import java.io.BufferedReader;
import java.io.FileReader;
import java.time.LocalDateTime;
public class rectangleDemo {
private static Rectangle[] rect ;
private static int count;
static private void loadFile( String filepath)
{
try { // Try catch expression to catch exception
String info=" ";
BufferedReader reader =null;
reader = new BufferedReader(new FileReader(filepath));
while ((info = reader.readLine()) != null)
{
String temp[] = info.split(",");
//
System.out.println(temp[0]);
System.out.println(temp[1]);
}
System.out.println("Database loaded successfully!");
reader.close();
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loadFile("rectangle.txt");
}
Input file
Output

#Tobit, This issue causing while reading the character. So just try setting the correct encoding format while reading the file. Kindly go through this link
Reading text file with UTF-8 encoding

The file 'rectangle.txt' might not be encoded in UTF-8 format. That is why your getting the extra special characters when you read the first line.
You can solve this in two ways,
Change the encoding of rectangle.txt to UTF-8 or
Set the encoding format while reading the file
I just created a UTF-16 file and replicated your issue. The solution would be,
BufferedReader reader =null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath),"UTF16"));

Related

Method to find a word in a file and replace a new words in a file(Java)

It couldnt replace the new word and place it in a new file.
I want to create a method that take 4 parameters, one with oldfile , one with new file, one with old word and one with new word and they are all of type string.
I also want to make it so that he case of the first letter the oldWord should be maintained when writing to the in the newFile, e.g. if oldWord was “Hit” and newWord was “Cab” then if “Hit” is found in the oldFile then “Cab” should be written to the newFile.
Im not allowed to use advanced java stuff like hashkeys and all that. Hope that enough infomaton and thank you in advance.
My code couldnt print the new words into the new file instead it just prints 4 more lines of the new words in the old file.
//////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class part2d {
public static void main(String[] args)
{
modifyFile("test.txt","modify.txt", "Hit", "Cab");
System.out.println("done");
}
static void modifyFile(String oldfile, String newfile, String oldString, String newString)
{
File fileToBeModified = new File("modify.txt");
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified,true);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Both your reader and your writer are using the fileToBeModified variable. This variable is being set to modify.txt statically for both, so you're not actually reading and writing a new file, instead you're reading then appending the same file content again.
Think about what file you're creating using the BufferedReader/FileReader and the FileWriter, and consider how these are being set.

Java: reading file and then writting data on a text file

How to read a file and then write the data into a .txt file in java? Below is my code. I am reading a file with extension .ivt. There are some tables in .ivt and reset is a text that describes what data is all about. I have to read the text stored in the file and then write it on a text file. I was able to get the data and write it on text file as well. But, when I open the text file and look at what is written, I see many lines of random symbols and spaces. Then, few lines are converted from English to French. I am struggling to find why this is happening. Does this problem occurs while reading data? or is there something wrong with the code?
package description;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
public class FileDescription
{
public static void main(String[] args)
{
// create variables
ArrayList<String> fileLines = new ArrayList<>();
String currLine;
// create file
File file = new File("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\Products.ivt");
FileInputStream fis = null;
BufferedReader br = null;
try
{
fis = new FileInputStream(file);
// construct buffered reader
br = new BufferedReader(new InputStreamReader(fis));
}
catch (FileNotFoundException e)
{
}
try
{
while((currLine = br.readLine()) != null)
{
// add line to the arrayList
fileLines.add(currLine);
}
}
catch (IOException e)
{
}
finally
{
// close buffered reader
try
{
br.close();
}
catch (IOException e)
{
}
}
// write ArrayList on file
PrintWriter pw = null;
try
{
pw = new PrintWriter("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt");
}
catch (IOException e)
{
}
for (int i = 0; i < fileLines.size(); i++)
{
pw.println(fileLines.get(i));
}
}
}
The code seems correct. Just remember to close output writer too. Without specify anything else, you are using plaftorm encoding. I think it's an encoding problem. You can try to read and write in UTF-8 encoding.
For the buffered reader
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("filename.txt"), StandardCharsets.UTF_8));
And for the writer
pstream = new PrintWriter(new OutputStreamWriter(
new FileOutputStream("E:\\Deep\\Personal Life\\Summer Education\\Grade 12 Physics\\Test\\ProductsO.txt"), StandardCharsets.UTF_8), true);
To edit result, use an editor with UTF-8.
Reference 1
Reference 2

Reverse file java program

I am trying to get a program to work. The input is a source file with lines of text. The output is a target file with the original line of text but in reversed.
ex.
abcd --> dcba
efgh hgfe
1234 4321
I have looked at a couple of similar questions, but they have gone about this in a different way than I have, and that doesn't exactly solve this individual problem. I have read it through and I think I am just over thinking this. I would greatly appreciate input on why my code is not outputting at all to the target file. I made a stack trace, and it prints all the way through perfectly fine.
Thanks,
code:
(command line arguments: source2.txt target2.txt
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java. util.Scanner;
/**
This program copies one file to another.
*/
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
String source = args[0];
String target = args[1];
File sourceFile=new File(source);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(target);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
What output are you seeing??
PrintWriter suppresses IOException and sets an error flag instead; you should use an
OutputStreamWriter().
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
Also, don't handle an exception with "something went wrong"; at the very least dump the stack trace so you know what and where it went wrong.
That said, I would probably output each line read to the console, like so:
System.out.println("** Read ["+s+"]");
to confirm I was actually reading the file.
import java.io.*;
import java.util.*;
class Driver {
public static void main(String[] args) {
ReverseFile demo = new ReverseFile();
demo.readFile("source2.txt");
demo.reverse("target2.txt");
}
}
class ReverseFile {
// Declare a stream of input
DataInputStream inStream;
// Store the bytes of input file in a String
ArrayList<Character> fileArray = new ArrayList<Character>();
// Store file sizes to see how much compression we get
long inFileSize;
long outFileSize;
// Track how many bytes we've read. Useful for large files.
int byteCount;
public void readFile(String fileName) {
try {
// Create a new File object, get size
File inputFile = new File(fileName);
inFileSize = inputFile.length();
// The constructor of DataInputStream requires an InputStream
inStream = new DataInputStream(new FileInputStream(inputFile));
}
// Oops. Errors.
catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
// Read the input file
try {
// While there are more bytes available to read...
while (inStream.available() > 0) {
// Read in a single byte and store it in a character
char c = (char)inStream.readByte();
if ((++byteCount)% 1024 == 0)
System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");
// Print the characters to see them for debugging purposes
//System.out.print(c);
// Add the character to an ArrayList
fileArray.add(c);
}
// clean up
inStream.close();
System.out.println("Done!!!\n");
}
// Oops. Errors.
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
// Print the ArrayList contents for debugging purposes
//System.out.println(fileArray);
}
public void reverse(String fileName) throws IOException {
FileWriter output = new FileWriter(fileName);
for (int i = fileArray.size() - 1; i >= 0; i++) {
try {
output.write(fileArray.get(i));
}
catch (IOException e) {
e.printStackTrace();
}
}
output.close();
}
}
That should work. If not, tell me and I'll look into the problem further.
I did some modification to your code..
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
// String source = args[0];
// String target = args[1];
File sourceFile=new File("C:/Users/Ruchira/Downloads/in.txt");//input File Path
File outFile=new File("C:/Users/Ruchira/Downloads/out.txt");//out put file path
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(outFile);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
This will work

Writing a java program to remove the comments in same java program?

I am Writing a java program to remove the comments in the same java program.
I am thinking of using a file reader. But I'm not sure whether it will work.
Because two process will be using the same file.
But I think before executing the code, java file will make a .class file.
So if I use a filereader to edit the java file. It should not give me error that another process is already using this file.
Am I thinking correct?
Thanks in advance.
Yes, you can do that without any problems.
Note: Be careful with things like:
String notAComment = "// This is not a comment";
If you just want to remove comments from a Java program, why don't you do a simple search and replace using a regex, and convert all comments into an empty string?
Here's a verbose way of doing it, in Java:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
class Cleaner{
public static void main( String a[] )
{
String source = readFile("source.java");
System.out.println(source.replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)",""));
}
static String readFile(String fileName) {
File file = new File(fileName);
char[] buffer = null;
try {
BufferedReader bufferedReader = new BufferedReader( new FileReader(file));
buffer = new char[(int)file.length()];
int i = 0;
int c = bufferedReader.read();
while (c != -1) {
buffer[i++] = (char)c;
c = bufferedReader.read();
}
} catch (IOException e) {
e.printStackTrace();
}
return new String(buffer);
}
}
You are right, the are not two processes using the same file, your program will use the .class files and process the .java files. You may want to take a closer look at this page:
Finding Comments in Source Code Using Regular Expressions
Yes, using a FileReader will work. One thing to watch out is the FileEncoding if you might have non-English characters or work across different platforms. In Eclipse and other IDEs you can change the character set for a Java source file to different encodings. If unsure, it might be worth using:
InputStream in = ....
BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"));
..
and likewise when you are writing the output back out, use an OutputStreamWriter with UTF-8.
Have a look at the post Remove comments from String for doing your stuff. You may use either FileReader or java.util.Scanner class to read the file.
Its late but it may help some to remove all types of comments.
package com.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
class CommentRemover {
public static void main(String a[]) {
File file = new File("F:/Java Examples/Sample.java");
String fileString = readLineByLine(file);
fileString = fileString.replaceAll(
"(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)", "");
System.out.println(fileString);
}
private static String readLineByLine(File file) {
String textFile = "";
FileInputStream fstream;
try {
fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(
fstream));
String strLine;
while ((strLine = br.readLine()) != null) {
textFile = textFile + replaceComments(strLine) + "\n";
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return textFile;
}
private static String replaceComments(String strLine) {
if (strLine.startsWith("//")) {
return "";
} else if (strLine.contains("//")) {
if (strLine.contains("\"")) {
int lastIndex = strLine.lastIndexOf("\"");
int lastIndexComment = strLine.lastIndexOf("//");
if (lastIndexComment > lastIndex) { // ( "" // )
strLine = strLine.substring(0, lastIndexComment);
}
} else {
int index = strLine.lastIndexOf("//");
strLine = strLine.substring(0, index);
}
}
return strLine;
}
}
I made a open source library (CommentRemover on GitHub) for this necessity , you can remove single line and multiple line Java Comments.
It supports remove or NOT remove TODO's.
Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.
Little code snippet how to use it (There is 2 type usage):
First way InternalPath
public static void main(String[] args) throws CommentRemoverException {
// root dir is: /Users/user/Projects/MyProject
// example for startInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc.. goes like that
.removeTodos(false) // Do Not Touch Todos (leave them alone)
.removeSingleLines(true) // Remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
.setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
Second way ExternalPath
public static void main(String[] args) throws CommentRemoverException {
// example for externalInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc..
.removeTodos(true) // Remove todos
.removeSingleLines(false) // Do not remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
.setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
public class Copy {
void RemoveComments(String inputFilePath, String outputFilePath) throws FileNotFoundException, IOException {
File in = new File(inputFilePath);
File out = new File(outputFilePath);
BufferedReader bufferedreader = new BufferedReader(new FileReader(in));
PrintWriter pw = new PrintWriter(new FileWriter(out));
String line = null, lineToRemove = null;
while ((line = bufferedreader.readLine()) != null) {
if (line.startsWith("/*") && line.endsWith("*/")) {
lineToRemove = line;
}
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
}
}

Reading and displaying data from a .txt file

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

Categories

Resources