Check if txt file has text ,if so don't write the same text again? - file

So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.
[code]
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
try {
fileWriter = new FileWriter(GameDirectory() + "\\scraped.txt", true);
bufferedReader = new BufferedReader(new FileReader(GameDirectory() + "\\scraped.txt"));
lineNumberReader = new LineNumberReader(new FileReader(GameDirectory() + "\\scraped.txt"));
} catch (IOException e) {
e.printStackTrace();
}
printWriter = new PrintWriter(fileWriter);
try {
fileWriter.write(playerName + "\r\n");
lineNumberReader.skip(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
}
addMessage("Scraped " + lineNumberReader.getLineNumber() + " usernames!");
}
[/code]
I've tried this too but with this it doesn't even write anymore.
[code]
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
String lines;
try {
if ((lines = bufferedReader.readLine()) != null) {
if (!lines.contains(playerName)) {
bufferedWriter.write(playerName);
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
int linenumber = 0;
try {
while (lineNumberReader.readLine() != null) {
linenumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
[/code]

Related

Reading text files into array

I'm trying to store girl and boy names into an array.
I got most of the code except the storing the files into an array.
This is what girls.txt looks like
Emma 125125
Elaina 415545
Kim 545454
Boys.txt:
Devan 45645
Tom 4545
Chris 4879797
i need help storing the names and numbers from files into array boynames array and girlnames array. I show where i need help with comments in code
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1Names {
public static void main(String[] args) {
Scanner inputStream = null;
String[][] boynames = new String[1000][2];
String[][] girlnames = new String[1000][2];
String line = null;
boolean isFoundB = false;
boolean isFoundG = false;
try {
inputStream = new Scanner(new FileInputStream("boys.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file boys.txt");
System.exit(0);
}
Scanner inputStreamGirls = null;
try {
inputStreamGirls = new Scanner(new FileInputStream("girls.txt"));
} catch (FileNotFoundException e) {
System.out.println("Problem opening file girls.txt");
System.exit(0);
}
int count = 0;
while (count < 1000){
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
count++;
}
count = 0;
while (count < 1000 ){
inputStreamGirls = girlnames[count][0]; //here
inputStreamGirls = girlnames[count][1]; //here
count++;
}
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first name that you would like to find the popularity of.\n Be sure to capitalize the first letter of the name.\n");
String answer = keyboard.next();
count = 0;
while(count < 1000){
if (boynames[count][0] == answer){
System.out.println(boynames[count][0] + " is ranked " + count + " among boys with " + boynames[count][1] + " namings");
isFoundB = true;
}
if (girlnames[count][0] == answer){
System.out.println(girlnames[count][0] + " is ranked " + count + " among girls with " + girlnames[count][1] + " namings");
isFoundG = true;
}
count++;
}
if(isFoundB == false){
System.out.println(answer + " is not ranked among the top 1000 boy names.");
}
if(isFoundG == false){
System.out.println(answer + " is not ranked among the top 1000 girl names.");
}
inputStreamGirls.close();
inputStream.close();
keyboard.close();
}
}
You will need to call the scanner methods to actually read from the input file.
scanner.next() reads one string token from the input.
So instead of this part:
inputStream = boynames[count][0]; //Error here
inputStream = boynames[count][1]; //here
You would do:
boynames[count][0] = inputStream.next();
boynames[count][1] = inputStream.next();

C# Can't read some characters from a file

New to c# here, I have done some research about this problem but couldn't find anything, lack of vocabulary maybe.
My task here is to a read a huge file and to extract only the lines which are following the conditions.
Code I'm using to test some things:
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
while ((line = sr.ReadLine()) != null)
{
try
{
if (line.Contains("R ") | line.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N", "").Replace("+", ",").Replace("·", ",").Replace("?", ",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}
This is a part of the file :
R XRPA168VC
B A
L 手动紧急停堆
E XRPA300KS
A 反应堆停堆 汽轮机停机
R XRPR111VR
B IP
E F2/3(XRPR144KS, XRPR145KS, XRPR146KS)
What I noticed is that the letters aren't even letter if there chinese around it, for example I tried the condition line.Substring(0,1) == "R", it couldn't find those lines.
No matter what I do, my codes would only return this
XPR111VR
F2/3XRPR144KS, XRPR145KS, XRPR146KS
I really need to be able to extract every R and E lines.
I just tried to copy my whole doc into Notepad and put the encoding into UTF8,
seems to work afterward but not sure if it's reliable.
Try this...it works
using (StreamReader sr = new StreamReader("SPDS_Test.doc"))
{
string line;
string data;
List<string> Data = new List<string>();
while ((line = sr.ReadLine()) != null)
{
var utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(line);
string myString = utf8.GetString(utfBytes, 0,
utfBytes.Length);
try
{
if (myString.Contains("R ") || myString.Contains("E "))
{
data = line;
data = data.Remove(0, 1);
data= data.Replace(" ", "").Replace("N",
"").Replace("+", ",").Replace("·", ",").Replace("?",
",").Replace("(", "").Replace(")", "");
Data.Add(data);
}
}
catch (Exception e)
{
Console.WriteLine("--------", e);
Console.WriteLine("--------Press any to continue---------");
Console.ReadKey();
}
}
foreach (string d in Data)
{
Console.WriteLine(d);
Console.ReadKey();
}
}

getting an empty file when downloading : jsf

I want to download a file stored in system directory but when downloading the file in jsf page I get it empty.
This is my xhtml page :
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
and my managed bean :
#ManagedBean
#SessionScoped
public class HelloBean {
public void downloadFile() {
File file = new File("C:\\data\\contacts.doc");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
so How to solve it? Thanks in advance.
I think this code solve your problem.
public void download() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}

How to add a condition to read line by line and append text after each line

I want to read each line and find if my line says " Project", then take the substring of that line (substring, 8 - Anything after the word Project) as an example and copy it to the end of each line for every row of line after the fact and up until a new line reads " Project". It should keep looping until the end of my file. This is what I have so far. My script stops and only displays the first line that is being read.
private void CreateFile_Click(object sender, EventArgs e)
{
try
{
var list = new List<string>();
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
if ((line = sr.ReadLine()) == " PROJECT")
{
while ((line = sr.ReadLine()) != null)
{
list.Add(line + "DATA");
}
}
else
{
list.Add(line);
}
}
TextBox.Text = string.Join(Environment.NewLine, list.ToArray());
}
catch (Exception ex)
{
MessageBox.Show("An error has occurred" + ex.Message);
}
}
Maybe i have understood your requirement:
using (var sr = new StreamReader("C:\\File1.txt"))
{
string line;
string currentProject = null;
while ((line = sr.ReadLine()) != null)
{
int index = line.IndexOf(" PROJECT", StringComparison.OrdinalIgnoreCase);
if (index >= 0)
currentProject = line.Substring(index + 9);
else
list.Add(string.Format("{0} {1}",line, currentProject));
}
}
You have two ReadLine in the if which advances the reader to the next line.

Need help fixing a try, catch error

I am trying to write a method that prints information into an array. the directions are: Create a second method for WordPath:
makeWordArray that takes a String file name as input, and it returns either an array or an ArrayList that stores WordData objects.
First, the method should open the file with new FileReader(file), call the numLines method to get the number of lines in file, and then create an array or an ArrayList of that size.
Next, close the FileReader and reopen the file. This time use BufferedReader br = new BufferedReader(new FileReader(file)). Create a loop to run through the file calling br.readLine(). For each line that you read in from br.readLine(), call the parseWordData on that String to get a WordData and store the WordData object into the appropriate index of the array or ArrayList.
My code is:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
I am running int a problem where the variable newArray can not be found, I believe because it is in the try statement. Is there any way to reformat this to work?
Like this:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
You need to pull the declaration of the variable outside, but leave the assignment to that variable on the inside of the try.

Resources