Scanner scans = new Scanner(System.in);
System.out.print("Enter filename: ");
String thisfile = scans.nextLine();
File thatfile = new File(thisfile);
FileInputStream fileInput = new FileInputStream(thatfile);
int i;
while ((i = fileInput.read()) != -1) {
char a = (char) i;
}
I'm using the code above to get a file(a java program) and search the file by each character. How can I determine which line a certain character is in. For example if this was the program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
If I was on the S of System, how would I be able to correctly determine that it is in line 3, using code? Sorry if I'm not clear but it's hard to explain.
What about enhancing you loop like so
char newline_character = <whatever is appropriate for your file>;
int line = 0;
while ((i = fileInput.read()) != -1) {
char a = (char) i;
if (a==newline_character) { ++line; }
}
Related
Given the following:
import java.io.*;
public class WriteRead {
public void writeToFile(String filename) throws IOException {
FileWriter fw = new FileWriter(filename);
fw.write("testing");
fw.close();
}
public String readFromFile(String filename) throws IOException {
String str = "";
int characterInt = 0;
FileReader fr = new FileReader(filename);
while (characterInt != -1) {
characterInt = fr.read();
str += "" + (char) characterInt;
}
fr.close();
return str;
}
public static void main(String[] args) throws IOException {
WriteRead wR = new WriteRead();
wR.writeToFile("test.java");
System.out.println(wR.readFromFile("test.java"));
}
}
when I run the program it prints the following:
What is the symbol at the end of "testing" and what part of the program causes it to be there?
Use the following code-
while ((characterInt = fr.read()) != -1) {
str += "" + (char) characterInt;
}
since in last iteration when this reads -1 this appends ? in str so please check before adding.and as far as your display of testing0 is concern give me hexcode of this first.
Make the changes as below:
while ((characterInt = fr.read()) != -1) {
//characterInt = fr.read();
str += "" + (char) characterInt;
}
Read the char and compare it with -1 as EOF. You were appending the end of file char in string and then while loop condition was getting failed.
You are setting characterInt = fr.read(); inside your whileloop. You should set this either outside whileloop or in while()condition.
So as per your code, it will run for second iteration also because in second iteration, your characterInt is not equal to -1 (it is holding earlier value i.e. testing).
I have to write a code to take a text file, which contains integers and doubles, and to print the doubles in a file and the integers in another one. The text file is formatted in the following way:
double int int int
double int int int
...
double int int int
It is saved in the "raw.txt" file.
The output should look like:
int int int
int int int
...
int int int
This is what I have tried so far:
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writer = new PrintWriter(new File("sorted.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, count = 1;
while (reader.hasNext()) {
try {
temp = reader.nextInt();
}
catch (InputMismatchException e) {
reader.nextLine();
temp = (int) reader.nextDouble();
}
writer.print(temp);
if (count % 4 == 0)
writer.println();
count++;
}
writer.close();
reader.close();
}
}
The current code throws an InputMismatchException. All help is greatly appreciated.
Based on your provided code you only want to split the files and do not care about the double and int values itself. So you could handle the file as a normal text file and split the values by the separating blank character.
The snippet does some assumptions on the format of the raw.txt file and is not optimised. So it should be an easy task to amend it based on your needs.
public static void main(String[] args) throws IOException {
List<String> rawLines = Files.readAllLines(Paths.get("raw.txt"));
try (Writer intWriter = Files.newBufferedWriter(
Paths.get("int_values.txt"),
StandardOpenOption.CREATE_NEW);
Writer doubleWriter = Files.newBufferedWriter(
Paths.get("double_values.txt"),
StandardOpenOption.CREATE_NEW)) {
for (String line : rawLines) {
// the split might need to be amended if the values
// are not separated by a single blank
String[] values = line.split(" ");
// to be amended if there are not alway four values in a row
if (values.length != 4) {
continue;
}
doubleWriter.write(values[0]);
doubleWriter.write(System.lineSeparator());
intWriter.write(values[1]);
intWriter.write(' ');
intWriter.write(values[2]);
intWriter.write(' ');
intWriter.write(values[3]);
intWriter.write(' ');
intWriter.write(System.lineSeparator());
}
}
}
InputMismatchException can be thrown because it is nether Integer either Double
It is much better to read a part as a String and then decide
When it is deciding, it throws NumberFormatException which can be catched
In following code there are two writers separated as you wanted, It could looks better than this code maybe
I have corrected your writing to file. I havent tested it but I really think if you do writer.print(temp);, it will put all integers without spaces, which is useless then.
Try this code, but not tested
import java.io.*;
import java.util.*;
public class DATA {
public static void main(String[] args) throws FileNotFoundException {
PrintWriter writerInt = new PrintWriter(new File("sortedInt.txt"));
PrintWriter writerDou = new PrintWriter(new File("sortedDou.txt"));
Scanner reader = new Scanner(new File("raw.txt"));
int temp = 0, countInt = 1, countDou = 1;
while (reader.hasNext()) {
String next = reader.next();
try{
temp=Integer.parseInt(next);
writerInt.print(temp+" ");
if (countInt % 4 == 0)
writerInt.println();
countInt++;
}catch(NumberFormatException e){
try{
writerDou.print(Double.parseDouble(next)+" ");
if (countDou % 4 == 0)
writerDou.println();
countDou++;
}catch(NumberFormatException f){
System.out.println("Not a number");
}
}
}
writerInt.close();
writerDou.close();
reader.close();
}
}
I have three programs to write for my Object Oriented Programming course, all involving file input/output, each of which contain no compile errors, yet they do not do what they are supposed to in run time (they don't print to the outFile like they're supposed to).
I know that the input file is being read and saved in the correct location, because Eclipse would indicate if either of these was not the case.
Furthermore, I have not (to my knowledge) committed any of the common errors involving not including throws exceptions of closing the read/write files.
I am attaching the first of my i/o assignments here with the hopes that the other files have similar errors that I can fix as soon as I can figure out what's wrong with this one.
import java.io.*;
public class GreenK4_Lab8 {
public static void main(String[] args) throws IOException {
int[] numbers = new int[countLines()];
int i = 0;
for(i = 0; i < numbers.length; i++) {
numbers[i] = readValues(i);
}
printOdd(numbers);
}
public static int countLines() throws IOException {
BufferedReader inFile = new BufferedReader(
new FileReader( "Lab8_TestFile.txt" ) );
int lineNumber = 1;
String nextLine = inFile.readLine();
while( nextLine != null ) {
lineNumber ++;
}
inFile.close();
return lineNumber;
}
public static int readValues(int number) throws IOException {
BufferedReader inFile = new BufferedReader(
new FileReader( "Lab8_TestFile.txt" ) );
int value = 0;
for(int i = 0; i < number; i++) {
String nextLine = inFile.readLine();
value = Integer.parseInt( nextLine );
}
inFile.close();
return value;
}
public static void printOdd(int[] array) throws IOException {
PrintWriter outFile = new PrintWriter( "results.out" );
for(int i = 0; i < array.length; i++) {
int value = array[i];
if( value % 2 != 0)
outFile.println( value );
}
outFile.close();
}
}
The following are the contents of the Lab8_TestFile.txt
4
6
2
10
8
1
-1
-2147483648
2147483647
5
9
3
7
-7
As other commenters pointed out, change your code in countLines function from
String nextLine = inFile.readLine();
while( nextLine != null ) {
lineNumber ++;
}
to
while (inFile.readLine() != null) {
lineNumber ++;
}
With this change your program works as expected.
There are multiple things wrong with your code. Let´s start from the beginning: your countLines method does not work as intended and will create a infinite loop because your while-condition will never be evaluated to false (unless your file is empty):
// String nextLine = inFile.readLine();
// while(nextLine != null) {
while (inFile.readLine() != null) {
lineNumber++;
}
You may want to check Number of lines in a file in Java for a faster and better performing version of retrieving the line count of a file.
Additionally your readValues function opens the file for every line it wants to read, reads the file until that line and closes the file again -> BAD. What you should do instead is the following:
public static void readValues(int[] contentsOfFile) throws IOException {
BufferedReader inFile = new BufferedReader(new FileReader("Lab8_TestFile.txt"));
for(int i = 0; i < contentsOfFile.length; i++) {
String nextLine = inFile.readLine();
contentsOfFile[i] = Integer.parseInt( nextLine );
}
inFile.close();
}
However that is not pretty as well since you rely on a adequately sized int array to be passed in. If you still want to get the line count separately from reading the values, do so, but let the readValues handle the appropriate reading by itself. That could result in something like:
public static ArrayList<Integer> readValues() throws IOException {
BufferedReader inFile = new BufferedReader(new FileReader("Lab8_TestFile.txt"));
ArrayList<Integer> integerContents = new ArrayList<>();
String nextLine = null;
while ((nextLine = inFile.readLine()) != null) {
integerContents.add(Integer.parseInt(nextLine));
}
inFile.close();
return integerContents;
}
That way you parse the file only once for reading the values. If you need to get a int[] back, take a look at How to convert an ArrayList containing Integers to primitive int array? to get an idea on how to extract that from the given data structure.
Your main function might result in something like:
public static void main(String[] args) throws IOException {
int numberOfLines = countLines(); // technically no longer needed.
int[] intContents = convertIntegers(readValues());
printOdd(intContents);
}
I want to interchange the last 2 words in a java file.
The file is called text_d.txt and it contains:
Student learns programming java.
and this is the code(below).The output is the same and I don't understand why it does not change.
import java.nio.*;
import java.io.*;
import java.lang.*;
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp=new FileInputStream(f.getAbsolutePath());
BufferedReader _rd=new BufferedReader(new InputStreamReader(_inp));
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
for(int i = 0; i <= _b.length; i++) {
if(i == 2) {
String aux=_b[i];
_b[i]=_b[i+1];
_b[i+1]=aux;
break;
}
}
_p=_rd.readLine();
}
}
}
For reading, interchanging and writing the file, I suggest you to do something like this:
public class Test3 {
public static void main(String[] args) throws Exception {
String s2="text_t.txt";
File _newf = new File("text_d.txt");
changeOrder(_newf);
}
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
ArrayList<String[]> newFileContent = new ArrayList<String[]>();
String _p=_rd.readLine();
while (_p != null) {
String [] _b = _p.split(" ");
String temp = _b[_b.length - 2];
_b[_b.length - 2] = _b[_b.length - 1];
_b[_b.length - 1] = temp;
newFileContent.add(_b);
_p=_rd.readLine();
}
PrintWriter writer = new PrintWriter(f.getAbsolutePath(), "UTF-8");
for (String[] line : newFileContent) {
for (String word : line) {
writer.print(word);
}
writer.println();
}
writer.close();
}
There is two minor changes:
First I changed the for loop you used in your code, with 3 lines of code.
Second I used to add all of lines which changed in the while loop in an ArrayList of String arrays which could hold changes in order to save on the file in the future.
And after all, I used an instance of PrintWriter class which could write a file on the hard disk. and in a foreach loop, I wrote contents of new file on the input file.
You could try something like this:
public static void changeOrder(File f) throws Exception {
FileInputStream _inp = new FileInputStream(f.getAbsolutePath());
BufferedReader _rd = new BufferedReader(new InputStreamReader(_inp));
String _p = _rd.readLine();
while (_p != null) {
String [] _b=_p.split(" ");
String temp = _b[_b.length - 1];
_b[_b.length - 1] = _b[_b.length - 2];
_b[_b.length - 2] = temp;
_p = _rd.readLine();
}
}
But if you want the file to be updated you need to write the results to the file...You should use something to write to the file like a PrintWriter.
This should do the trick You want:
public static String changeOrder(File fileName) throws IOException {
Scanner file = new Scanner(fileName);
String line = file.nextLine();
line = line.replace('.', ' ');
String[] items = line.split(" ");
StringBuilder sb = new StringBuilder();
sb.append(items[0] + " ");
sb.append(items[1] + " ");
sb.append(items[3] + " ");
sb.append(items[2] + ".");
return sb.toString();
}
Expected result: Student learns java programming.
I currently have the following code:
public class Count {
public static void countChar() throws FileNotFoundException {
Scanner scannerFile = null;
try {
scannerFile = new Scanner(new File("file"));
} catch (FileNotFoundException e) {
}
int starNumber = 0; // number of *'s
while (scannerFile.hasNext()) {
String character = scannerFile.next();
int index =0;
char star = '*';
while(index<character.length()) {
if(character.charAt(index)==star){
starNumber++;
}
index++;
}
System.out.println(starNumber);
}
}
I'm trying to find out how many times a * occurs in a textfile. For example given a text file containing
Hi * My * name *
the method should return with 3
Currently what happens is with the above example the method would return:
0
1
1
2
2
3
Thanks in advance.
Use Apache commons-io to read the file into a String
String org.apache.commons.io.FileUtils.readFileToString(File file);
And then, use Apache commons-lang to count the matches of *:
int org.apache.commons.lang.StringUtils.countMatches(String str, String sub)
Result:
int count = StringUtils.countMatches(FileUtils.readFileToString(file), "*");
http://commons.apache.org/io/
http://commons.apache.org/lang/
Everything in your method works fine, except that you print the count per line:
while (scannerFile.hasNext()) {
String character = scannerFile.next();
int index =0;
char star = '*';
while(index<character.length()) {
if(character.charAt(index)==star){
starNumber++;
}
index++;
}
/* PRINTS the result for each line!!! */
System.out.println(starNumber);
}
int countStars(String fileName) throws IOException {
FileReader fileReader = new FileReader(fileName);
char[] cbuf = new char[1];
int n = 0;
while(fileReader.read(cbuf)) {
if(cbuf[0] == '*') {
n++;
}
}
fileReader.close();
return n;
}
I would stick to the Java libraries at this point, then use other libraries (such as the commons libraries) as you become more familiar with the core Java API. This is off the top of my head, might need to be tweaked to run.
StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while (s != null)
{
sb.append(s);
s = br.readLine();
}
br.close(); // this closes the underlying reader so no need for fr.close()
String fileAsStr = sb.toString();
int count = 0;
int idx = fileAsStr('*')
while (idx > -1)
{
count++;
idx = fileAsStr('*', idx+1);
}